我正在处理php数组,但我有获取父数组索引的问题。在这里我想找到标题的父索引,所以我尝试通过循环查找它,但是如果标题是数组,我找不到索引。如果标题是数组,如何获取父索引
<?php
$Arr = [
[
"title" => ["news", "nasional", "internasional", "regional", "metropolitan", "sains", "pendidikan"],
"url" => "AAA",
],
[
"title" => ["seleb", "news"],
"url" => "BBB"
],
[
"title" => "travel",
"url" => "CCC"
]
];
foreach($Arr as $value) {
$key = array_search("seleb", array_column($Arr , 'title'));
echo $key; // should return index parent is [1]
}
?>
答案 0 :(得分:0)
您正在传递整个数组,而不是传递循环的当前值
foreach ($Arr as $key => $value) {
$keyChild='';
$keyChild = array_search("seleb", $value);
if ($keyChild != null && empty($keyChild)) {
echo $key;
}
}
答案 1 :(得分:0)
尝试此操作以找到父索引
$Arr = [
[
"title" => ["news", "nasional", "internasional", "regional", "metropolitan", "sains", "pendidikan"],
"url" => "AAA",
],
[
"title" => ["seleb", "news"],
"url" => "BBB"
],
[
"title" => "travel",
"url" => "CCC"
]
];
foreach($Arr as $key => $value) {
if(is_array($value['title'])){
if(in_array("seleb", $value['title']))
echo $key;
}
}
答案 2 :(得分:0)
这是另一种做到这一点的方法,它减少了嵌套并增加了可重用性
<?php
$arr = [
[
"title" => ["news", "nasional", "internasional", "regional", "metropolitan", "sains", "pendidikan"],
"url" => "AAA",
],
[
"title" => ["seleb", "news"],
"url" => "BBB"
],
[
"title" => "travel",
"url" => "CCC"
]
];
function findIndex($search, $array) {
$found = array_filter($array, function ($value) use ($search) {
if (!is_array($value)) $value = [$value];
return array_search($search, $value) !== false;
});
return key($found);
}
$titles = array_column($arr, 'title');
echo findIndex('seleb', $titles); // 1
findIndex
将返回父索引或对是否找到结果进行加深处理的空值。
还有这部分:
$titles = array_column($arr, 'title');
可以将'title'
作为另一个参数传递到函数中。