views:

251

answers:

2

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.

+3  A: 

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.

KernelM
+2  A: 

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;
}
Andrew Moore
That assumes though that the two arrays have sequential numerical keys.
KernelM
It assumes that the two arrays are of the same size. In my case, they are not. The count array is equal to or less than the id/name array.
Thomas Owens
(However, I didn't specify the size constraints in my original posting.)
Thomas Owens