[英]how to check the same value or more than one in looping arrays and make new keys as a differentiator on php
我想檢查循環數組中的值是否相同或不止一個,還有其他條件。 我應該怎么辦?
在我制作的數組中[title] => Kue Lapis,有兩個,而[title] => Kue Nastar只有一個
我發現了相同的問題,但我希望得到不同的結果。
我想要的值是否等於或大於一個,它將創建一個新的鍵,例如[confirm] = true,否則創建一個新的鍵[confirm] = false
這是我的數組
Array
(
[0] => Array
(
[order] => 127
[title] => Kue Nastar
)
[1] => Array
(
[order] => 128
[title] => Kue Lapis
)
[2] => Array
(
[order] => 129
[title] => Kue Lapis
)
)
我想要這個結果
Array
(
[0] => Array
(
[order] => 127
[title] => Kue Nastar
[comfirm] => 0
)
[1] => Array
(
[order] => 128
[title] => Kue Lapis
[comfirm] => 1
)
[2] => Array
(
[order] => 129
[title] => Kue Lapis
[comfirm] => 1
)
)
您將需要循環數組兩次。
一次獲取每個標題的計數,一次創建您期望的輸出。
// Create associative array of title and count
foreach($arr as $val){
if(!isset($counts[$val['title']])) $counts[$val['title']] = 0;
$counts[$val['title']]++;
}
// Add count 1/0 to array
foreach($arr as &$val){
if($counts[$val['title']] > 1){
$val['confirm'] = 1;
}else{
$val['confirm'] = 0;
}
}
var_dump($arr);
您可以將array_count_values
和array_column
與array_walk
array_column
使用
$tCounts = array_count_values(array_column($a, 'title'));
array_walk($a, function(&$v, $k) use($tCounts){
$v['confirm'] = $tCounts[$v['title']] > 1 ? true : false;
});
使用內置函數array_walk , array_count_values和array_column ,您只需要一行
array_walk($arr, function(&$elem, $index, $occurrence)
{
$elem['comfirm'] = (int)($occurrence[$elem['title']] > 1);
},
array_count_values(array_column($arr, 'title')));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.