在 PHP 中获取多维数组中的较低值

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

我有数组A:
enter image description here
我有并输入文本,在这种情况下输入值为

level
,例如它是
5
。 ,结果一定是
2
。我想从输入文本值中找到数组 A 中的lower level。我不知道如何进入PHP。帮帮我,谢谢

php arrays multidimensional-array filtering
3个回答
1
投票

循环遍历$arrayA的所有数组

foreach($arrayA as $array)
{
   // Check each array has level value 2 or not 
   if ($array['level'] == 2)
   {
       // found value
       echo "found the array";
   }
}

0
投票

要获取具有特定级别的数组

2
,您可以使用array_filter(),例如,

$result = array_filter($arrayA, function($k) {
    return $k['level'] == 2;
});
print_r($result);

使其动态化,要获得

parent_ohp_id
为空白的最低级别,然后使用,

$result = array_filter($arrayA, function($k) {
    return $k['parent_ohp_id'] == "";// this is the root level because it has no parent id
});
print_r($result);

0
投票

一种方法是使用

usort()
函数对
level
键上的表格进行排序,然后获取数组的第一个元素:

<?php

  $array = [
    [
      'john' => 'Snow',
      'level' => 5,
    ],
    [
      'john' => 'Cena',
      'level' => 8,
    ],
    [
      'john' => 'Kennedy',
      'level' => 2,
    ],
    [
      'john' => 'Glenn',
      'level' => 12,
    ],
  ];

  usort($array, function ($a, $b) {
    return $a['level'] - $b['level'];
  });

  echo current($array)['john']; // This will display "Kennedy".

另一种方法是使用

foreach
循环并将级别值与之前的迭代进行比较:

  $lowest = $array[0];

  foreach ($array as $item) {
    if ($item['level'] < $lowest['level']) {
      $lowest = $item;
    }
  }

  echo $lowest['john']; // This will also display "Kennedy".
© www.soinside.com 2019 - 2024. All rights reserved.