结合基于数组的off值

时间:2013-06-04 16:50:40

标签: php arrays

好吧,我一直把头发拉出来!我已经尝试过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)

等等。

1 个答案:

答案 0 :(得分:1)

你可以试试这个

对于您的产品阵列,请执行以下操作:

$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'