首页 > 解决方案 > 如何从数组中制作 1 个相同 id 的口袋

问题描述

<?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 不同时,它会创建另一个数组

标签: phparrays

解决方案


你很亲密。您不需要$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


推荐阅读