从二维数组中获取所有一级键,其中在行中的任何位置找到指定值

问题描述 投票:0回答:3

我有这个多维数组:

$numbers = array (
    "one_digit" => array (1,2,3,4,5),
    "two_digits" => array (20,21,22,23,24,25),
    "three_digits" => array (301,302,303,304,304),
    "mixed_digits" => array (9,29,309,1)
);

我需要一种方法在

$numbers
数组中搜索以下内容:

  • 搜索数字 20 是否在任何

    $numbers
    数组中并回显找到的位置

    $find1 = m_array_search("20", $numbers);
    echo "i've found the searched value in ".$find1." subarray of $numbers";
    

    结果:

    "i've found the searched value in two_digits subarray of $numbers"
    
  • 搜索数字 1 是否在任何

    $numbers
    数组中并回显找到的位置

    $find2 = m_array_search("1", $numbers);
    echo "i've found the searched value in ".$find2." subarray of $numbers";
    

    结果:

    "i've found the searched value in two_digits,mixed_digits subarray of $numbers"
    

因此函数必须能够发现一个或多个子数组中的存在。

php arrays multidimensional-array filter
3个回答
2
投票

使用

in_array
函数的简单解决方案:

$search = 1;
$keys = [];
foreach ($numbers as $k => $v) {
    if (is_array($v) && in_array($search, $v)) $keys[] = $k;
}

echo "I've found the searched value in ". implode(', ', $keys) ." subarray". ((count($keys) > 1)? "s":"") ." of \$numbers";

输出:

I've found the searched value in one_digit, mixed_digits subarrays of $numbers

1
投票

检查此内容并告诉我是否对您有帮助。

<?php
function array_find_deep($array, $search, $keys = array())
{
    foreach($array as $key => $value) {
        if (is_array($value)) {
            $sub = array_find_deep($value, $search, array_merge($keys, array($key)));
            if (count($sub)) {
                return $sub;
            }
        } elseif ($value === $search) {
            return array_merge($keys, array($key));
        }
    }

    return array();
}


$numbers = array (
    "one_digit" => array (1,2,3,4,5), 
    "two_digits" => array (20,21,22,23,24,25),
    "three_digits" => array (301,302,303,304,304),
    "mixed_digits" => array (9,29,309,1)
);

var_dump(array_find_deep($numbers, 20));

var_dump(array_find_deep($numbers, 1));

var_dump(array_find_deep($numbers, 301));

var_dump(array_find_deep($numbers, 309));

?>

您可以将结果存储在像

$result  = array_find_deep($numbers, 20);
这样的变量中,然后尝试
echo $result[0]
这将给出在哪个数组中找到该值的结果。


0
投票

您可以在循环中使用 array_search() 尝试 -

$numbers = array (
    "one_digit" => array (1,2,3,4,5),
    "two_digits" => array (20,21,22,23,24,25),
    "three_digits" => array (301,302,303,304,304),
    "mixed_digits" => array (9,29,309,1)
);

function search_value($array, $value)
{
  $result = array();
  foreach($array as $key => $sub) {
    // check if element present in sub array
    if(array_search($value, $sub) !== false) {
      // store the key
      $result[] = $key;
    }
  }
  return $result;
}

var_dump(search_value($numbers, 1));
var_dump(search_value($numbers, 5));

输出

array(2) {
  [0]=>
  string(9) "one_digit"
  [1]=>
  string(12) "mixed_digits"
}
array(1) {
  [0]=>
  string(9) "one_digit"
}
© www.soinside.com 2019 - 2024. All rights reserved.