在PHP多维数组中搜索 [英] Search in php multidimensional array
问题描述
我的项目中有一个这样的分层数组:
I have a hierarchical array in my project like this:
$Array = array(
array(
'Id' => 1,
'Title' => 'Some Text1',
'Children' => array(
array(
'Id' => 11,
'Title' => 'Some Text11',
'Children' => array(
array(
'Id' => 111,
'Title' => 'Some Text111',
),
array(
'Id' => 112,
'Title' => 'Some Text112',
'Children' => array(
array(
'Id' => 1121,
'Title' => 'Some Text1121',
)
)
)
)
),
array(
'Id' => 12,
'Title' => 'Some Text12',
'Children' => array(
array(
'Id' => 121,
'Title' => 'Some Text121',
)
)
)
)
),
array(
'Id' => 2,
'Title' => 'Some Text2',
)
);
我想在中搜索我的字符串(例如 Some Text1121)在此数组中添加标题
索引并返回其路径,例如搜索'Some Text1121'
之后,我想返回此结果:
I want to search my string (such as 'Some Text1121') in 'Title'
index in this array and return it's path such as after search 'Some Text1121'
I want to return this result:
"1 -> 11 -> 112 -> 1121"
或者当我搜索 Some字符串时,返回数组中的所有路径。
,请帮助我,谢谢。
Or when I Search 'Some' string, return all path in array. please help me, thanks.
推荐答案
我很快就给您写了东西。它不是完美的,但是您可以理解:
I've quickly written you something. It's not perfect, but you get the idea:
<?php
function searchRec($haystack, $needle, $pathId = Array(), $pathIndex = Array()) {
foreach($haystack as $index => $item) {
// add the current path to pathId-array
$pathId[] = $item['Id'];
// add the current index to pathIndex-array
$pathIndex[] = $index;
// check if we have a match
if($item['Title'] == $needle) {
// return the match
$returnObject = new stdClass();
// the current item where we have the match
$returnObject->match = $item;
// path of Id's (1, 11, 112, 1121)
$returnObject->pathId = $pathId;
// path of indexes (0,0,1,..) - you might need this to access the item directly
$returnObject->pathIndex = $pathIndex;
return $returnObject;
}
if(isset($item['Children']) && count($item['Children']>0)) {
// if this item has children, we call the same function (recursively)
// again to search inside those children:
$result = searchRec($item['Children'], $needle, $pathId, $pathIndex);
if($result) {
// if that search was successful, return the match-object
return $result;
}
}
}
return false;
}
// useage:
$result = searchRec($Array, "Some Text11");
var_dump($result);
// use
echo implode(" -> ", $result->pathId);
// to get your desired 1 -> 11 -> 112
EDIT :被重写以使该函数实际返回内容。现在,它将返回一个带有匹配项的对象,Id的路径和(数组)索引的路径。
EDIT: rewritten to make the function actually return something. It now returns an Object with the matching item, the path of Id's and the path of (array-) Indexes.
这篇关于在PHP多维数组中搜索的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!