我有一个多维数组,我需要一些范围值,如:我想搜索10,000到20,000 数组示例如下:
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
)
)
如何从数组中获取选定范围的值。
答案 0 :(得分:2)
$min = 10000;
$max = 20000;
$selectedRange = array_filter(
$myOriginalArray,
function ($value) use ($min, $max) {
return (($value >= $min) && ($value <= $max));
}
);
虽然如果这些数据来自数据库查询,最好使用WHERE子句对其进行过滤
答案 1 :(得分:1)
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;
}
这将根据您的最小值和最大值
返回已过滤的数组答案 2 :(得分:0)
好的,我能给你的最好的答案就是写一些像array_walk这样的东西。 第二个提示(如果你需要对新数组进行其他操作)是使用array_filter,如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 />\n";
}
}
$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);