I have a multidimensional array where I need to some range values like : I want to search from 10,000 to 20,000 Array example is given below :
Array
(
[0] => Array
(
[name] => sample1
[price] => 10000
)
[1] => Array
(
[name] => sample1
[price] => 18000
)
[2] => Array
(
[name] => sample1
[price] => 22000
)
[3] => Array
(
[name] => sample1
[price] => 14000
)
)
How I can get selected range of values from array.
function filterArray($search_array, $min, $max)
{
$returned_array = [];
foreach($search_array as $array_item)
{
$price = $array_item["price"];
if($price >= $min && $price <= $max) $returned_array[] = $array_item;
}
return $returned_array;
}
This will return a filtered array given your min and max values
Using array_filter()
$min = 10000;
$max = 20000;
$selectedRange = array_filter(
$myOriginalArray,
function ($value) use ($min, $max) {
return (($value >= $min) && ($value <= $max));
}
);
Though if this data is coming from a database query, it would be better do filter it there using a WHERE clause
Ok so, the best answere I can give you is writing something like array_walk for this. The second offere (if you need to do other operations with the new array) is to use array_filter, as shown in the buttom.
<?php
$min = 14000;
$max = 19000;
function array_walk_example($item, $key)
{
global $min,$max;
if ($item["price"] > $min && $item["price"] < $max){
echo $key. $item["price"]."<br />
";
}
}
$array = Array
(
0 => Array
(
"name" => "sample1",
"price" => 10000
),
1 => Array
(
"name" => "sample2",
"price" => 18000
),
2 => Array
(
"name" => "sample3",
"price" => 22000
),
3 => Array
(
"name" => "sample4",
"price" => 14000
),
);
array_walk($array, "array_walk_example");
function array_filter_example($value){
global $min,$max;
var_dump($value);
return (($value['price'] >= $min) && ($value['price'] <= $max));
}
$range = array_filter($array,"array_filter_example");
var_dump($range);