尝试编写一个函数来搜索数组中的值,依赖于子元素中的引用

问题描述 投票:-1回答:1

我怎样才能实现这种行为?我试图写一个函数来实现这个逻辑,但由于某种原因它不起作用。这是我试图做http://sandbox.onlinephpfunctions.com/code/638fc7796a8918e2b7ef1469b746c29adba8d0cd的链接

<?php

    $test = [
      'deepLink' => [
        1,2,3,4,5, 'testMe'
      ],    
      'base' => [ // child for (2 and target)
        'SuperMan',
        'deepLink'  // expected true, if we call array_search_for_target_key($test, 'target', 'testMe')
      ],    
      2 => [
        'base' // link on child (base)
      ],    
      'target' => [
        2   // link on child (2)
      ],
    ];

function array_search_for_target_key($array = array(), $targetKkey, $search) {
   $res = false;
    foreach($array as $k => $v) {
        if ($k === $targetKkey && in_array($search, $v)) {
              $res = true;
        } else {
           if (is_array($v)) {
               foreach ($v as $nested) {
                 $array =  $nested;
                 $res = array_search_for_target_key($array, $nested, $search);   
               }
           }
        }
    }

    return $res;
}

var_dump( array_search_for_target_key($test, 'target', 'SuperMan'));

所以我解决了我的问题,这里是qazxsw poi

php arrays nested parent-child
1个回答
0
投票

你在这部分得到错误

link

$array = $nested; $res = array_search_for_target_key($array, $nested, $search); 不是一个数组,所以它会抛出一个错误。这是

$array

所以改变你的代码:

Invalid argument supplied for foreach() 

有了这个

foreach ($v as $nested){
    $array =  $nested;
    $res = array_search_for_target_key($array, $nested, $search);   
} 

更改后,我们将遇到新的错误

foreach ($v as $nested) {
    $res = array_search_for_target_key($v, $nested, $search);   
}

要解决这个问题,我们需要检查变量是否是一个数组。

从这个改变你的代码:

in_array() expects parameter 2 to be array, integer given

有了这个

 if ($k === $targetKkey && in_array($search, $v))

还在你的:

 if ($k === $targetKkey && is_array($v) && in_array($search, $v))

if ($k === $targetKkey && is_array($v) && in_array($search, $v)) { $res = true; } 改为$res = true。如果我们已经找到目标,我们不想继续。将return true;改为$k === $targetKkey$k == $targetKkey将返回2 === '2',所以将其更改为false

这是整个代码

==

<?php $test = [ 'deepLink' => [ 1,2,3,4,5, 'testMe' ], 'base' => [ // child for (2 and target) 'SuperMan', 'deepLink' // expected true, if we call array_search_for_target_key($test, 'target', 'testMe') ], 2 => [ 'base' // link on child (base) ], 'target' => [ 2 // link on child (2) ], ]; function array_search_for_target_key($array, $targetKkey, $search) { $res = false; foreach($array as $k => $v) { if ($k == $targetKkey && is_array($v) && in_array($search, $v)) { return true; } else { if (is_array($v)) { foreach ($v as $nested) { $res = array_search_for_target_key($v, $nested, $search); } } } } return $res; } var_dump( array_search_for_target_key($test, 'target', 'SuperMan'));

© www.soinside.com 2019 - 2024. All rights reserved.