Question

I have two arrays. One contains id=>count and the other contains id=>name. I'm trying to produce a single array that is name=>count. Any suggestions on a straightforward way to do this?

I have looked at the Array Functions in the PHP Manual and didn't see anything that stood out as doing what I want, so I'm guessing I'll need a combination of functions, but I'm having trouble coming up with something that's not convoluted.

Was it helpful?

Solution

Something like:

foreach($countA as $id => $count)
{
    $newArray[$nameA[$id]] = $count;
}

This does assume that the keys are in correspondence between the two arrays, since your requirements are ambiguous otherwise.

OTHER TIPS

Use array_combine...

$countArray = array(0 => 1, 1 => 5);
$namesArray = array(0 => "Bob", 1 => "Alice");

$assocArray = array_combine($namesArray, $countArray);

Edit: Here is a revised solution for the new requirements expressed in comment #2

$assocArray = array();
foreach($namesArray as $id => $name) {
    $assocArray[$name] = (array_key_exists($id, $countArray)) ? $countArray[$id] : 0;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top