Russel Riehle
Russel Riehle

Reputation: 267

Merge two arrays keeping numeric key

I have two comma separated strings like this:

$items = "banana,apple,grape";
$colors = "yellow,red,green";

So I exploded them to get arrays. Like this:

$items = explode(',',$items);
$colors = explode(',',$colors);

But I'm stuck here. I want to merge these 2 arrays ($items and $colors) but keeping an order like this:

$mergedArray[0]['item'] should print "banana".
$mergedArray[0]['color'] should print "yellow".

$mergedArray[1]['item'] should print "apple".
$mergedArray[1]['color'] should print "red".

$mergedArray[2]['item'] should print "grape".
$mergedArray[2]['color'] should print "green".

I tried array_merge but it doesnt seem to solve this problem. Thanks.

Upvotes: 1

Views: 67

Answers (3)

Hussein
Hussein

Reputation: 1153

$items = explode(',',$items);
$colors = explode(',',$colors);
$final = [];
foreach ($items as $key => $item){
    $item_mod = [
     'item' => $item,
     'color' => $colors[$key]
    ];
array_push($final,$item_mod);
}

//based on the order this should output banana
echo $final[0]['item'];

Upvotes: 0

Gufran Hasan
Gufran Hasan

Reputation: 9373

You can also do it by using for loop as:

$items = "banana,apple,grape";
$colors = "yellow,red,green";

$items = explode(',',$items);
$colors = explode(',',$colors);
$results =array();
for($i=0; $i<count($items);$i++){
    $results[$i]['item'] = $items[$i];
    $results[$i]['color'] = $colors[$i];
}

echo "<pre>";
print_r( $results );
echo "</pre>";

Upvotes: 0

Eddie
Eddie

Reputation: 26844

You can array_map the 2 arrays

$items = "banana,apple,grape";
$colors = "yellow,red,green";

$items = explode(',',$items);
$colors = explode(',',$colors);

$results = array_map(function($i, $c) {
    return array(
        'item' => $i,
        'color' => $c,
    );
}, $items, $colors);

echo "<pre>";
print_r( $results );
echo "</pre>";

This will result to:

Array
(
    [0] => Array
        (
            [item] => banana
            [color] => yellow
        )

    [1] => Array
        (
            [item] => apple
            [color] => red
        )

    [2] => Array
        (
            [item] => grape
            [color] => green
        )

)

Upvotes: 3

Related Questions