phparraysmultidimensional-arrayfilteringcontiguous

Get rows from a 2d array from one nominated column value to another


I am working on an array and I would like to get all the arrays between two values of an array eg

$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',
  ),
);

So that given username and password I want to get the following

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

Simply because it comes after the array with the value of username and before the array with value of password.


Solution

  • Simply loop with two condition like below

    $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);
    

    Live demo : https://eval.in/879235