PHP映射和拆分多维数组

时间:2017-09-19 02:43:21

标签: php multidimensional-array mapping

我正在研究2个多维数组:

$array1 = array(
    0 => array(
        'items' => array(
            1 => array('79-' => 'abc','80-'=>'123'),
            2 => array('79-' => 'Mapping item1','80-'=>'123'),
            3 => array('79-' => 'abc','80-'=>'123')
        )
    ),
    1 => array(
        'items' => array(
            1 => array('79-' => 'Mapping item2','80-'=>'123'),
        )
    )
);

这是第二个数组:

$array2 = array(
    2 => array(
        "A" => 'Mapping item1',
        "B" => array(1 => 'product1', 2 => 'product2', 3 => 'product3')
    ),
    3 => array(
        "A" => 'Mapping item2',
        "B" => array(1 => 'product4', 2 => 'product5', 3 => 'product6')
    )
);

我试图通过键值79-映射2个数组,并对array1进行更改。这是我的代码。

foreach ($array1 as $key => $orders) {
    $items = $orders['items'];
    $itemIndex = 1;
    foreach ($items as $k => $item) {
        foreach ($array2 as $row) {
            if (strpos($item['79-'], $row['A']) !== false) {
                foreach ($row['B'] as $ite) {
                    items[ $itemIndex ]['79-'] = $ite;
                    $itemIndex++;
                }
            }
        }
        $itemIndex++;
    }

    $orders['items'] = $items;
    $array1[ $key ] = $orders;
}

我想返回一个如下所示的数组,但我的代码不起作用。

$expectedArray = array(
    [0]=> array(
       ['items'] => array(
          [1]=>array('79-'=>'abc','80-'=>'123'),
          [2]=>array('79-'=>'product1','80-'=>'123'),
          [3]=>array('79-'=>'product2','80-'=>'123'),
          [4]=>array('79-'=>'product3','80-'=>'123'),
          [5]=>array('79-'=>'abc','80-'=>'123')
       )
    ),
    [1]=>array(
       ['items'] => array(
          [1]=>array('79-'=>'product4','80-'=>'123'),
          [2]=>array('79-'=>'product5','80-'=>'123'),
          [3]=>array('79-'=>'product6','80-'=>'123'),          
       )
    )
);

任何人都知道如何解决这个问题,请帮忙。我已经工作了好几个小时了。

1 个答案:

答案 0 :(得分:1)

希望这个会有所帮助。我们在这里使用foreacharray_columnarray_map

Try this code snippet here

$column=array_column($array2,"B","A");
foreach ($array1 as $key => $itemsArray)
{
    $finalArray=array();//maintaining a final array
    foreach($itemsArray["items"] as $itemKey => $item)
    {
        if(isset($column[$item["79-"]]))//checking key in the column array
        {
            $result=array_map(function($value) use($item){
               unset($item["79-"]);
               return array("79-"=>$value)+$item;
            },$column[$item["79-"]]);
            $finalArray=$finalArray+$result;//appending array with + operator
        }
        else
        {
            $finalArray[]=$item;
        }
    }
    $array1[$key]["items"]=$finalArray;//overwriting final array to existing one
}
print_r($array1);