我有一個這樣的數組:如何在PHP中整合這個數組的重複元素?
$array = array(
0 => array("ordernumber" => "1", "name" => "John", "product" => "laptop", "component" => "memory"),
1 => array("ordernumber" => "1", "name" => "John", "product" => "laptop", "component" => "cpu"),
2 => array("ordernumber" => "1", "name" => "John", "product" => "desktop", "component" => "cpu"),
3 => array("ordernumber" => "2", "name" => "Pete", "product" => "monitor", "component" => "")
);
它包含了從不同的訂單數據,但你可以看到一個訂單可以包含多個購買的產品,每個產品可以包含不同的「分量」。在這個陣列中有很多重複的數據,所以我想把它變成這樣:
$array = array(
0 => array(
"order" => array(
"ordernumber" => "1", "name" => "John"
),
"products" => array(
0 => array(
"name" => "laptop",
"components" => array("memory", "cpu")
),
1 => array(
"name" => "desktop",
"components" => array("cpu")
)
)
),
1 => array(
"order" => array(
"ordernumber" => "2", "name" => "Pete"
),
"products" => array(
0 => array(
"name" => "monitor",
"components" => array()
)
)
)
);
這將是一個很好的方法來做到這一點?
使用foreach循環並相應地修改數據。你有什麼嘗試? – jitendrapurohit
我對數組不熟悉,所以我甚至無法想象循環(或者組成新數組)實際上應該是什麼樣子。感謝下面的解決方案,我對未來如何解決類似問題有了更清晰的瞭解。 – Marc