从二维数组中从一个指定列值获取行到另一个[重复]

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

我正在处理一个数组,我想获取数组的两个值之间的所有数组,例如

$fields = array(
 'a' => array(
  'name' => 'username',
  'type' => 'text',
  ),
 'b' => array(
  'name' => 'birthday',
  'type' => 'text',
  ),
 'c' => array(
  'name' => 'address',
  'type' => 'text',
  ),
 'd' => array(
  'name' => 'password',
  'type' => 'text',
  ),
);

所以给定

username
password
我想得到以下

 'b' => array(
  'name' => 'birthday',
  'type' => 'text',
  ),
 'c' => array(
  'name' => 'address',
  'type' => 'text',
  ),

仅仅因为它位于值为

username
的数组之后、值为
password
的数组之前。

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

简单地循环两个条件,如下所示

$start = "username";
$end = "password";
$new = array();
$flag = false;
foreach($fields as $key=>$value){
  if($value["name"] == $start){
    $flag = true;
    continue;
  }
  if($value["name"] == $end){
    break;;
  }
  if($flag){
    $new[$key] = $value;
  }
}
print_r($new);

现场演示:https://eval.in/879235


0
投票
function getArraysBetweenNames($name1, $name2, $array)
{
    $return = [];
    $foundName1 = false;

    foreach ($array as $key => $item) {
        if ($foundName1) {
            if ($item["name"] == $name2)
                break;

            $return[$key] = $item;
        } elseif ($item["name"] == $name1) {
            $foundName1 = true;
        }

    }

    return $return;
}

print_r(getArraysBetweenNames("username", "password", $fields));

0
投票

您可以将

name
值提取到数组中,进行搜索并使用搜索结果位置进行切片:

$names  = array_column($fields, 'name');
$result = array_slice($fields, $i=array_search('username', $names)+1,
                                  array_search('password', $names)-$i);

-1
投票
$fields = array(
 'a' => array(
  'name' => 'username',
  'type' => 'text',
  ),
 'b' => array(
  'name' => 'birthday',
  'type' => 'text',
  ),
 'c' => array(
  'name' => 'address',
  'type' => 'text',
  ),
 'd' => array(
  'name' => 'password',
  'type' => 'text',
  ),
);

如果您想要来自字段的 b,c 数组,您只需

echo $fields[b][name];
echo $fields[b][type]; 
echo $fields[c][name];
echo $fields[c][type];
© www.soinside.com 2019 - 2024. All rights reserved.