我有一个多维数组,想通过特定的payment_status找到一个数组:下面是我的数组,我想通过payment_status返回一个数组。
[orders] => Array
(
[0] => Array
(
[total_price] => 995.94
[avg] => 995.940000
[count] => 1
[payment_status] => 1
)
[1] => Array
(
[total_price] => 779.64
[avg] => 779.640000
[count] => 1
[payment_status] => 2
)
[2] => Array
(
[total_price] => 1763.49
[avg] => 1763.490000
[count] => 1
[payment_status] => 3
)
function get_sub_array((int)$payment_status) {
}
我该怎么做?谢谢!
$arr = array('orders' => array
(
0 => Array
(
'total_price' => 995.94,
'avg' => 995.940000,
'count' => 1,
'payment_status' => 1
),
1 => Array
(
'total_price' => 779.64,
'avg' => 779.640000,
'count' => 1,
'payment_status' => 2
),
2 => Array
(
'total_price' => 1763.49,
'avg' => 1763.490000,
'count' => 1,
'payment_status' => 3
)
));
function get_sub_array($payment_status,$arr) {
$arrRet = array();
foreach($arr as $key=>$val){
if($val['payment_status'] == $payment_status)
array_push($arrRet,$val);
}
return $arrRet;
}
$arrRes = get_sub_array(1,$arr['orders']);
print_r($arrRes);
我想这可以。
function get_sub_array($arr, $payment_status) {
foreach($arr as $item) {
if($item['payment_status'] === $payment_status) {
return $item;
}
}
}
假设您想要检索具有相同状态的多个订单,您可以这样做:
function get_sub_array($orders, $payment_status) {
$result = array();
foreach ($orders as $order) {
if ($order['payment_status'] == $payment_status) {
array_push($result, $order);
}
}
return $result;
}
您可以使用array_filter
。例如,如果您想要一个包含所有支付状态为3
的值的子数组:
$sub_array = array_filter($arr['orders'],function($val){
return $val['payment_status'] === 3;
});