Map values between two arrays to generate a flat, associative array

39 Views Asked by At

I have two arrays, one is a list of status IDs and the corresponding numbers of records that are that status ID. The second array is the names of the statuses. I'd like to tie them together so I have one array I can use in a graph.

The first array is

[
    ["status" => NULL, "number" => "2355"],
    ["status" => "1", "number" => "1"],
    ["status" => "2", "number" => "1"],
    ["status" => "3", "number" => "1"],
    ["status" => "4", "number" => "1"],
    ["status" => "7", "number" => "1"]
]

and the second is

[
    "Undelivered",
    "Sent",
    "Bounced",
    "Delivered",
    "Opened",
    "Clicked",
    "Logged In",
    "Completed",
    "Committed"
]

I have this code

$data = $this->_get_email_status();
$statii = $this->model->option_status;
foreach($statii as $index => $status) {
    $data[$index][TC_STATUS] = $status;
}

Which almost does what I want, except each array key has an array in it, which isn't quite what I need. This is what I am getting

[
    ["status" => "Undelivered", "number" => "2355"],
    ["status" => "Sent", "number" => "1"],
    ["status" => "Bounced", "number" => "1"],
    ["status" => "Delivered", "number" => "1"],
    ["status" => "Opened", "number" => "1"],
    ["status" => "Clicked", "number" => "1"],
    ["status" => "Logged In"],
    ["status" => "Completed"],
    ["status" => "Committed"]
]

And this is what I wanted:

[
    "Undelivered" => "2355",
    "Sent" => "1",
    "Bounced" => "1",
    "Delivered" => "1",
    "Opened" => "1",
    "Completed" => "1"
]

I'm sure there must be a way to do this programmatically but I seem to be going around in circles!

2

There are 2 best solutions below

1
user14989191 On

Figured it out, thanks to @CBroe , I made a new array and got the output as I wanted...

 $data = $this->_get_email_status();
            $statii = $this->model->option_status;
            $s = array();
            foreach($statii as $index => $status) {
                $s[$status] = $data[$index]['number'];
            }
0
mickmackusa On

Iterate over the first array and map the numeric/null values to the corresponding value in the second array.

It is a little string that you have a null value in the payload, but simply cast that null to an integer and it will become 0 as desired.

Code: (Demo)

$result = [];
foreach ($array1 as ['status' => $i, 'number' => $n]) {
    $result[$array2[(int) $i]] = $n;
}
var_export($result);