在多维数组中查找子数组

时间:2014-06-14 10:56:00

标签: php arrays multidimensional-array

我有一个多维数组,想通过特定的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) {

}

我该怎么做? 谢谢!

4 个答案:

答案 0 :(得分:1)

我认为这会奏效。

function get_sub_array($arr, $payment_status) {
    foreach($arr as $item) {
        if($item['payment_status'] === $payment_status) {
            return $item;
        }
    }
}

答案 1 :(得分:1)

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

答案 2 :(得分:0)

假设您想要检索具有相同状态的多个订单,您可以执行以下操作:

    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;
    }

答案 3 :(得分:0)

您可以使用array_filter。例如,如果您想要一个包含付款状态为3的所有值的子数组:

$sub_array = array_filter($arr['orders'],function($val){ 
    return $val['payment_status'] === 3; 
});