我有两个逗号分隔的字符串,如下所示:
$items = "banana,apple,grape";
$colors = "yellow,red,green";
所以我将它们爆炸以获得数组。像这样:
$items = explode(',',$items);
$colors = explode(',',$colors);
但是我被困在这里。 我想合并这两个数组($ items和$ colors)但保持这样的顺序:
$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".
我尝试过array_merge,但它似乎无法解决这个问题。 感谢。
答案 0 :(得分:3)
你可以array_map
2个阵列
$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>";
这将导致:
Array
(
[0] => Array
(
[item] => banana
[color] => yellow
)
[1] => Array
(
[item] => apple
[color] => red
)
[2] => Array
(
[item] => grape
[color] => green
)
)
答案 1 :(得分:0)
$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'];
答案 2 :(得分:0)
您也可以使用for loop
作为:
$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>";