Home > Back-end >  get key of multi dimension array (PHP Language)
get key of multi dimension array (PHP Language)

Time:02-18

Hi I have a problem regarding multi-dimension array. I have a set of array looking like this

array:3 [▼
  0 => array:1 [▼
    "tree" => "0"
  ]
  1 => array:1 [▼
    "tree" => "2"
  ]
  2 => array:1 [▼
    "tree" => "0"
  ]
]

the array is from

dd($this->treeArray);

how do I want to get the array which the value is 0. Expected result/filter For example:

array:2 [▼
  0 => array:1 [▼
    "tree" => "0"
  ]
  1 => array:1 [▼
    "tree" => "0"
  ]
]

or 

array:1 [▼
  0 => array:1 [▼
    "tree" => "2"
  ]
]

if changing the index is impossible, its ok.. Thank you

CodePudding user response:

do you want in_array()?

$arraysContainingZero=[];
foreach($this->treeArray as $wutkey => $wut){
    if(in_array("0", $wut, true)){
        $arraysContainingZero[$wutkey] = $wut;
    }
}
var_dump($arraysContainingZero);

CodePudding user response:

There are a lots of build in function in PHP that is useful for operating on an array. You can see the full list here: https://www.php.net/manual/en/ref.array.php

One of the function is called array_filter (https://www.php.net/manual/en/function.array-filter.php). The function iterates over each value in the array passing them to the callback function. If the callback function returns true, the current value from array is returned into the result array.

So in your case, you want to call the array_filter with a callback that return true if the value is 0. Example:

$input = [
        [ 'tree' => 1 ],
        [ 'tree' => 0 ],
        [ 'tree' => 0 ],
    ];
    
$output = array_filter($input, function($arr) {
    return $arr['tree'] === 0;
});
var_dump($output);

// result 
array(2) {
  [1]=>
  array(1) {
    ["tree"]=>
    int(0)
  }
  [2]=>
  array(1) {
    ["tree"]=>
    int(0)
  }
}

CodePudding user response:

As you are using Laravel, you could use array helper such as this

You can use like this:

use Illuminate\Support\Arr;

$newTreeArray = Arr::where($this->treeArray, function ($tree) => $tree['tree'] === "0");
  • Related