如何从数组制作1个具有相同ID的口袋

时间:2019-04-10 10:03:55

标签: php arrays

<?php
$a = [["product"=>"another2", "id"=>112],["product"=>"xyz", "id"=>113], ["product"=>"lmn", "id"=>113],["product"=>"abc", "id"=>113],  ["product"=>"another", "id"=>112]];

$data = [];
$products = [];

foreach ($a as $b) {

  $products[]["product"] = $b["product"];

  $data[$b["id"]] = $products;

}

echo "<pre>";
print_r($data);

,输出为

  Array ( [112] => Array ( [0] => Array ( [product] => another2 ) [1] => Array ( [product] => xyz ) [2] => Array ( [product] => lmn ) [3] => Array ( [product] => abc ) [4] => Array ( [product] => another ) ) [113] => Array ( [0] => Array ( [product] => another2 ) [1] => Array ( [product] => xyz ) [2] => Array ( [product] => lmn ) [3] => Array ( [product] => abc ) ) ) 

我想制作1个相同ID的口袋。 如果所有数组的id为112,则赚1个口袋。例如我需要

Array
(
    [112] => Array
        (


            [0] => Array
                (
                    [product] => xyz
                )

            [2] => Array
                (
                    [product] => lmn
                )

            [3] => Array
                (
                    [product] => abc
                )



        )

    [113] => Array
        (
            [0] => Array
                (
                    [product] => another
                )
            [1] => Array
                (
                    [product] => another2
                )

                           )
        )
)

如何获得此输出?谁能帮助我实现这一目标。如果id相同,则我需要1个数组,因为id不同时,它会生成另一个数组

3 个答案:

答案 0 :(得分:1)

您非常亲密。您无需每次都定义$products。只需在数组上循环(将$k保存为键)并分配。

考虑:

$a = [["product"=>"another2", "id"=>112],["product"=>"xyz", "id"=>113], ["product"=>"lmn", "id"=>113],["product"=>"abc", "id"=>113],  ["product"=>"another", "id"=>112]];

$data = [];
foreach ($a as $k => $b) {
  $data[$b["id"]][$k]["product"] =  $b["product"];
}

现在$data将成为您的愿望输出。

实时示例:3v4l

答案 1 :(得分:1)

检查以下工作代码:

$a = [["product"=>"another2", "id"=>112],["product"=>"xyz", "id"=>113], ["product"=>"lmn", "id"=>113],["product"=>"abc", "id"=>113],  ["product"=>"another", "id"=>112]];

$products = [];

foreach ($a as $b) {    
  $products[$b["id"]][]["product"] = $b["product"];
}

echo "<pre>";
print_r($products);

答案 2 :(得分:1)

尝试这个

$arr1 = [];
foreach($arr as $k => $v){
 if(array_key_exists($v['id'], $arr1))
    $arr1[$v['id']][]['product'] = $v['product'];
 else
    $arr1[$v['id']][]['product'] = $v['product'];
}