views:

109

answers:

4

I have 2 separate arrays, one is just the id's the other is the percentage Id's: Array ( [0] => 3 [1] => 4 [2] => 5 [3] => 6 [4] => 7 }

Percent array: Array ( [0] => 28 [1] => 39 [2] => 17 [3] => 28 [4] => 23

So it would end up like: Array ( [0] => Array

  (
    [id] => 3
    [percent] => 28
   )

and so on for each of the pairs?

+1  A: 

simply loop through the elements of the array (0..4) and add items to your new array.

(I'm not including sample code, because this sounds like a homework assignment!)

rmeden
Hm didn't think about that homework part ;)
Jani Hartikainen
A: 

I don't think there's any builtin way to do that, so you'll have to utilize a loop such as..

$pairs = array();
for($i = 0, $len = count($ids); $i < $len; $i++) {
    $pair = array(
        'id' => $ids[$i],
        'percent' => $percents[$i]
    );

    $pairs[] = $pair;
}
Jani Hartikainen
why no just 'for($i = 0; $i < count($ids); $i++)'?
Philippe Gerber
It's so that you won't run count() on every iteration, possibly saving some time. I don't think it affects things much with smaller arrays, but I've grown kind of used to writing for loops like that
Jani Hartikainen
wow. thanks! just did some benchmarking and there is some significant difference with larger arrays. :D
Philippe Gerber
-edit- it's not like I have been using count() with big arrays, but your notation just seems like good practice. :-)
Philippe Gerber
A: 

AFAIK you can't do that in a trivial way, however you can do something like array_combine($ids, $percentages);

Alix Axel
I'd probability do this assuming $ids are unique.
gradbot
A: 

A good idea might be to use two loops to account for the case where the arrays don't have equal member counts like this:

$ids = array(...);
$percent = array(...);
$combined = array();
foreach($ids as $index => $id) {
    $combined[$index]['id'] = $id;
}
foreach($percent as $index => $percentage) {
    $combined[$index]['percent'] = $percentage;
}
zacharydanger
why loop twice when the indexes are the same?
Philippe Gerber
@phphil - As stated above, in case the arrays don't have equal counts.
zacharydanger