有没有办法查看数组内部并拔出具有匹配值的键的键?有人问这样的问题,但我找不到任何结论。
所以如果我的数组看起来像这样
Array
(
[0] => Array
(
[title] => Title 1
[type] =>
[message] =>
)
[1] => Array
(
[title] => Title 2
[type] =>
[message] =>
)
[2] => Array
(
[title] => Title 3
[type] =>
[message] =>
)
[3] => Array
(
[title] => Title 2
[type] => Limited
[message] => 39
)
[4] => Array
(
[title] => Title 4
[type] => Offline
[message] => 41
)
[5] => Array
(
[title] => Title 5
[type] =>
[message] =>
)
我想得到这个
Array
(
[1] => Array
(
[title] => Title 2
[type] =>
[message] =>
)
[3] => Array
(
[title] => Title 2
[type] => Limited
[message] => 39
)
)
答案 0 :(得分:2)
$titlesCount = array_count_values(array_map(function($item){ return $item['title']; }, $input));
$output = array_filter($input, function($item) use(&$titlesCount){ return $titlesCount[$item['title']] > 1; });
其中$ input是原始数组,$ output是结果。
它计算标题的每个不同值,并仅返回多次出现的值。
答案 1 :(得分:0)
@ Bugs的答案比这个更好,但是我仍然发布它,因为我觉得我的解决方案更容易理解:
$arr = Array
(
Array
(
"title" => "Title 1",
"type" => NULL,
"message" => NULL
),
Array
(
"title" => "Title 2",
"type" => NULL,
"message" => NULL
),
Array
(
"title" => "Title 3",
"type" => NULL,
"message" => NULL
),
Array
(
"title" => "Title 2",
"type" => "Limited",
"message" => 39
),
Array
(
"title" => "Title 4",
"type" => "Offline",
"message" => 41
),
Array
(
"title" => "Title 5",
"type" => NULL,
"message" => NULL
)
);
//create a "map" that will hold all the values of previous titles
$map = array();
$res = array();
foreach ($arr as $key => $subarr) {
foreach ($subarr as $subkey => $value) {
if($subkey === "title"){
if($map[$value]){ //if such a title already exists, add both of them to the result
$res[] = $arr[$map[$value]];
$res[] = $arr[$key];
}
else { // add the current into the map
$map[$value] = $key;
}
}
}
}
print_r($res);
<强>输出:强>
Array
(
[0] => Array
(
[title] => Title 2
[type] =>
[message] =>
)
[1] => Array
(
[title] => Title 2
[type] => Limited
[message] => 39
)
)
答案 2 :(得分:-1)
foreach($array as &$subarray) {
if(is_array($subarray) && isset($subarray['title']) && $subarray['title'] == 'Title 2') {
$matches[] = $subarray;
}
}
可以很容易地包含在一个以子阵列键和值为参数的函数中。