php - 如何从数组中制作 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 不同时,它会创建另一个数组
解决方案
你很亲密。您不需要$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
推荐阅读
- odoo - 在 Odoo 11 中打开和关闭库存
- c# - 数据读取器与指定的“StoredProcedureReturn”不兼容
- ruby-on-rails - Rails will_paginate 如何生成完整的url?
- python-3.x - ModuleNotFoundError:没有名为“pystruct.models.utils”的模块
- angular - 无法以角度 6 导出到剑道网格中的 excel 整个网格数据
- c# - C# WPF 风格的 SaveFileDialog
- go - 获取完整的 UTC 偏移格式
- ios - 具有固定宽度的居中按钮会中断 NSLayoutConstraint
- xmlhttprequest - 从 facebook 加载 XMLHttpRequest 即时游戏返回空结果,即使我在从服务器获取数据之前刚刚保存了数据
- r - 根据 r 中的字符串向量添加到 url 中的文本