如何按键和值组合两个数组?

时间:2019-11-21 14:13:29

标签: php arrays

这是我的数组“产品”:

fi_FI

这是我的数组“类别”:

array:3 [▼
  0 => array:8 [▼
    "uuid" => "78f895684c"
    "Name" => "test1"
  ]
  1 => array:8 [▼
    "uuid" => "f71db561ba"
    "Name" => "Zwei"
  ]
  2 => array:8 [▼
    "uuid" => "3e231651de"
    "Name" => "Test3"
  ]
]

我尝试创建一个新的数组,将我的产品归类。 这是我的方法:

array:3 [▼
  "78f895684c" => "pink"
  "f71db561ba" => "blue"
  "3e231651de" => "pink"
]

我期望的结果是:

 foreach ($products as $key => $value) {
   $test = $category[$value["uuid"]];
   $new[$test] = array();
   array_push($new,$value);
 }

但是我的结果是:

array:5 [▼
  "blue" => 
     [0] => array:2 [▼
      "uuid" => "f71db561ba"
      "Name" => "Zwei"
  ]
  "pink" => 
    [1] => array:2 [▼
       "uuid" => "78f895684c"
       "Name" => "test1"
    [2] => array:2 [▼
    "uuid" => "3e231651de"
    "Name" => "Test3"
  ]
]

2 个答案:

答案 0 :(得分:1)

您使用以下方法将元素推入错误的数组中

array_push($new,$value);

因为您需要将其插入$new[$test]中,所以相反

array_push($new[$test],$value);

还要检查$new[$test]是否已经存在,否则创建数组:

if(!$new[$test]) $new[$test] = array();

所以最后的代码是

foreach ($products as $key => $value) {
   $test = $category[$value["uuid"]];
   if(!$new[$test]) $new[$test] = array();
   array_push($new[$test],$value);
} 

答案 1 :(得分:1)

您可以执行以下操作:$new[$cat][] = $value;

示例:

$new = array();

foreach ($products as $prod) {
  $cat = $category[$prod['uuid']];

  $new[$cat][] = $prod;
}

正在运行的演示here