PHP在未知深度的多维数组中搜索 [英] php searching in multidimensional array of unknown depth

查看:219
本文介绍了PHP在未知深度的多维数组中搜索的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试选择由json_decode()构造的数组的数据. 原则上,它是一个未知维的多数组.

I try to select the data of an array that was constructed by json_decode(). In principle it is an multiarray of unknown dimension.

首先,我想递归搜索此数组中的值.下一步,我想获取高维的其他一些值.所以这是一个例子:

First of all, I want to search recursively for a value in this array. As a next step I want to get some other values of the upper dimension. So here is an example:

我搜索:"2345"

....
$json[3][6]['journal']['headline']="news"
$json[3][6]['journal']['article']=2345
....
$json[8]['journal']['headline']="weather"
$json[8]['journal']['article']=2345
....

之后,我想获取元素headline的值(返回新闻"和天气")

After that I want to get the value of the element headline (returning "news" and "weather")

2345元素的尺寸可能不同!

It might be that the element 2345 can be found in different dimensions!!!

推荐答案

只需创建一个用于编译未知数组的函数.试试这个

just create a function for compile unknown array. try this

$json[1][6]['journal']['headline']="news";
$json[1][6]['journal']['article']=2345;
$json[3][6]['journal']['headline']="HOT";
$json[3][6]['journal']['article']=2345;
$json[8]['journal']['headline']="weather";
$json[8]['journal']['article']=2345;
$json[10]['journal']['headline']="weather";
$json[10]['journal']['article']=2345;

$GLOBALS['list_scan'] = array();
$result = array();

foreach ($json as $key => $value) 
{
    if (is_array($value)) {
        _compile_scan($key, $value);
    }
}

echo "<pre>";
print_r($GLOBALS['list_scan']);
echo "</pre>";

$search = "2345";
$keyword = "article";
$keyFinder = "headline";

foreach ($GLOBALS['list_scan'] as $key => $value)
{
    if ($value == $search)
    {
        $addr = substr($key, 0, -(strlen($keyword))).$keyFinder;
        if (!empty($GLOBALS['list_scan'][$addr]))
        {
            $result[] = $GLOBALS['list_scan'][$addr];
        }
    }
}
echo "<pre>";
print_r($result);
echo "</pre>";


function _compile_scan($index, $value)
{
    $pointer =& $GLOBALS['list_scan'];

    foreach ($value as $key => $val) 
    {
        $temp = '';
        $temp = $index.'|'.$key;
        if (is_array($val))
        {
            // $pointer[$temp] = $val;
            _compile_scan($temp, $val);
        }
        else $pointer[$temp] = $val;
    }
}

输出:

Array
(
    [1|6|journal|headline] => news
    [1|6|journal|article] => 2345
    [3|6|journal|headline] => HOT
    [3|6|journal|article] => 2345
    [8|journal|headline] => weather
    [8|journal|article] => 2345
    [9|journal|headline] => Others
    [9|journal|article] => 234521
)
Array
(
    [0] => news
    [1] => HOT
    [2] => weather
)

这篇关于PHP在未知深度的多维数组中搜索的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆