【问题标题】:Finding Array/Object sequence in php在php中查找数组/对象序列
【发布时间】:2014-02-18 12:03:57
【问题描述】:

我有以下数组作为输入:

$test = array(
            array(
                'cat','d'=>'fox',
            ),
            'x' => array(
                'y'=> array('fox'),
            ),
        );

我需要在这个数组中找到值“fox”的序列。如果给定数组作为输入,是否有任何函数可以生成序列。 IE。输出应采用以下格式

$test[0]['d']
$test['x']['y'][0]

【问题讨论】:

  • 您是否尝试过编写自己的递归函数来执行此操作?
  • 你试过什么?我所看到的只是一个具有标准方法来获取序列的数组,没有用户创建的函数
  • 我只是在搜索是否有任何 php 函数可以让我生成序列。 IE。我们有 print_r 来显示整个数组。我认为可能存在类似的功能
  • @dainis abols 如果不存在函数,我将编写自己的代码
  • 我认为到目前为止,php 中还没有库函数可以提供精确的数组序列,尽管这样的函数对开发人员非常有用

标签: php arrays object sequence


【解决方案1】:

看完cmets,答案很简单。您只是询问是否有任何内置的 PHP 函数可以执行此任务。

回答:不,没有内置函数,你自己写的。它应该导致递归算法。 (甚至是迭代的,因为递归总是可以被迭代代替)。

这里有一个可以完成这项工作的函数。请注意,我已经用迭代替换了递归,以便调整算法:

$a = array(
    array(
        'cat','d'=>'fox',
    ),
    'x' => array(
        'y'=> array('fox'),
    ),
);

function pathto($value, $array) {
    // init stack
    $stack = array(array($array, 'array'));
    do {
        // get first value from stack
        list ($current_value, $current_path) = array_shift($stack);

        // if current is a scalar value then compare to the input
        if($current_value === $value) {
            echo $current_path . PHP_EOL;
            continue;
        }

        // push array childs to stack
        if(is_array($current_value)) {
            foreach($current_value as $k => $v) {
                $k = is_string($k) ? "'$k'" : $k; 
                // push child and path to file
                array_push($stack, array (
                    $v, $current_path . '[' . $k . ']' 
                )); 
            }   
        }   
    } while (!empty($stack));
}

pathto('fox', $a);

输出:

$test[0]['d']
$test['x']['y'][0]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-01-07
    • 1970-01-01
    • 1970-01-01
    • 2014-12-18
    • 1970-01-01
    • 2021-01-15
    • 2019-04-01
    相关资源
    最近更新 更多