我想知道如何迭代陣列以計算 PHP 中的元素,接下來我會嘗試,
foreach ($items as $item) {
$tm[$item->provider->name] = [];
foreach ($items as $item) {
$tm[$item->provider->name][$item->product->brand->name] = isset($tm[$item->provider->name][$item->product->brand->name]) ? $tm[$item->provider->name][$item->product->brand->name] 1 : $tm[$item->provider->name][$item->product->brand->name] = 1;
}
}
但是我得到了一個錯誤的結果,我得到了一個陣列,但是我得到了一個非常高的數字,就像迭代了很多次一樣
陣列的結構如下
[{
"id": 1,
"product": {
"id": 1,
"brand": {
"id": 1,
"name": "iphone"
}
},
"provider": {
"id": 1,
"name": "at&t"
}
},
{
"id": 2,
"product": {
"id": 2,
"brand": {
"id": 2,
"name": "iphone"
}
},
"provider": {
"id": 1,
"name": "at&t"
}
},
{
"id": 3,
"product": {
"id": 3,
"brand": {
"id": 3,
"name": "iphone"
}
},
"provider": {
"id": 1,
"name": "t-mobile"
}
}]
uj5u.com熱心網友回復:
IIUC,您正在嘗試計算product->brand->name每個provider->name. 您可以使用以下代碼執行此操作:
$tm = array();
foreach ($items as $item) {
$product = $item->product->brand->name;
$provider = $item->provider->name;
$tm[$provider][$product] = ($tm[$provider][$product] ?? 0) 1;
}
print_r($tm);
輸出(用于您的樣本資料):
Array
(
[at&t] => Array
(
[iphone] => 2
)
[t-mobile] => Array
(
[iphone] => 1
)
)
3v4l.org 上的演示
uj5u.com熱心網友回復:
從您的代碼示例中,您顯然想計算陣列中每個“事物”的出現次數,否則count()可能就足夠了......
盡管您正在做很多作業來預初始化計數陣列 - 這是完全不需要的:閱讀有關自動激活的資訊。
像這樣的代碼可能就足夠了(我在這里沒有遵循您的示例代碼 - 您需要根據您的需要進行調整):
$counters = [];
foreach ($items as $item)
@$counters[$item->name][$item->model] ;
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/514928.html
標籤:php数组多维数组前锋
