组合一个基于off值的数组


Combining an array based off value

好吧,我一直在为这件事烦恼!我曾尝试使用SQL调用将功能添加到产品中,但由于产品是一行而功能不是一行,因此它为每个产品创建了一个新行。我想我可以将它们都添加到一个数组中,并根据产品ID将它们连接起来。下面是数组

array
  0 => 
    array
  'id_product' => string '9' (length=1)
  'name' => string 'Brady ENV100 MAXX Enhanced Sorbents' (length=35)
  'number_sold' => string '6' (length=1)
  'link_rewrite' => string 'brady-env100-maxx-enhanced-sorbents' (length=35)
  'id_image' => string '27' (length=2)
 1 => 
array
  'id_product' => string '10' (length=2)
  'name' => string 'Brady GP100 MAXX Enhanced Heavy Pad' (length=35)
  'number_sold' => string '3' (length=1)
  'link_rewrite' => string 'brady-gp100-maxx-enhanced-heavy-pad' (length=35)
  'id_image' => string '29' (length=2)
array
 0 => 
array
  'id_product' => string '9' (length=1)
  'name' => string 'Height' (length=6)
  'value' => string '5' (length=1)
 1 => 
array
  'id_product' => string '9' (length=1)
  'name' => string 'Width' (length=5)
  'value' => string '5' (length=1)
 2 => 
array
  'id_product' => string '9' (length=1)
  'name' => string 'Depth' (length=5)
  'value' => string '5' (length=1)
  3 => 
array
  'id_product' => string '9' (length=1)
  'name' => string 'Weight' (length=6)
  'value' => string '5' (length=1)
 4 => 
array
  'id_product' => string '10' (length=2)
  'name' => string 'Height' (length=6)
  'value' => string '10' (length=2)

我已经看了很多教程,但似乎不能得到任何工作。我想让它看起来像

array
0 => 
array
'id_product' => string '9' (length=1)
'name' => string 'Brady ENV100 MAXX Enhanced Sorbents' (length=35)
'number_sold' => string '6' (length=1)
'link_rewrite' => string 'brady-env100-maxx-enhanced-sorbents' (length=35)
'id_image' => string '27' (length=2)
name' => string 'Height' (length=6)
'value' => string '5' (length=1)
 'name' => string 'Width' (length=5)
'value' => string '5' (length=1)
'name' => string 'Depth' (length=5)
'value' => string '5' (length=1)

你可以试试这个

对于product数组,这样做:

$result = array();
foreach ($mainItems as $item){
    $result[$item["id_product"]] = $item;
}

对于每个属性数组

foreach($attributes as $val){
    if (array_key_exists($val["id_product"], $result)){
        $result[$val["id_product"]][$val["name"]] = $val["value"];
    }
}
你最终应该得到一个类似于 的数组
[9] => array(
       [id_product] => 9
       [name] => "Brady ENV100 MAXX Enhanced Sorbents"
       [number_sold] => "6"
       [link_rewrite] => "brady-env100-maxx-enhanced-sorbents"
       [id_image] => "27"
       [Height] => 5
       [Width] => 5
       [Depth] => 5  
),
[10] => array(
       [id_product] =>  '10' 
       [name] =>  'Brady GP100 MAXX Enhanced Heavy Pad' 
       [number_sold] => '3'
       [link_rewrite] =>  'brady-gp100-maxx-enhanced-heavy-pad' 
       [id_image] =>  '29'