Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/image-processing/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 合并两个保留数字键的数组_Php - Fatal编程技术网

Php 合并两个保留数字键的数组

Php 合并两个保留数字键的数组,php,Php,我有两个逗号分隔的字符串,如下所示: $items = "banana,apple,grape"; $colors = "yellow,red,green"; $mergedArray[0]['item'] should print "banana". $mergedArray[0]['color'] should print "yellow". $mergedArray[1]['item'] should print "apple". $mergedArray[1]['color'] sh

我有两个逗号分隔的字符串,如下所示:

$items = "banana,apple,grape";
$colors = "yellow,red,green";
$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".
所以我把它们分解成数组。像这样:

$items = explode(',',$items);
$colors = explode(',',$colors);
但我被困在这里了。 我想合并这两个数组($items和$colors),但保持如下顺序:

$items = "banana,apple,grape";
$colors = "yellow,red,green";
$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".
我尝试了数组合并,但似乎解决不了这个问题。
谢谢。

您可以
数组\u映射
这两个数组

$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>";

您也可以使用
for loop
来执行此操作,如下所示:

$items=“香蕉、苹果、葡萄”;
$colors=“黄、红、绿”;
$items=分解(“,”,$items);
$colors=分解(“,”,$colors);
$results=array();

对于($i=0;$i您想要什么?您只需打印此
$items[0]
将打印香蕉,
$colors[0]
将打印黄色,或将它们合并
$mergedArray=['item'=>$items,'color'=>$colors];
$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>";