多维数组值(如果存在)

时间:2019-05-04 09:48:26

标签: php multidimensional-array

我想在数组中带状态为1的结果。(对不起,我不会说英语) 我的数组是;

 [10100002] => Array
        (
            [0] => stdClass Object
                (
                    [ID] => 664
                    [barcode] => 10100002                   
                    [status] => 0
                )

            [1] => stdClass Object
                (
                    [ID] => 1339
                    [barcode] => 10100002                   
                    [status] => 0
                )

        )
 [10100004] => Array
        (
            [0] => stdClass Object
                (
                    [ID] => 1116
                    [barcode] => 10100004                   
                    [status] => 1
                )

            [1] => stdClass Object
                (
                    [ID] => 1826
                    [barcode] => 10100004                    
                    [status] => 0
                )

        )

在10100002中,两个状态为0,但是第二个数组找到状态1.。如果多个数组中的状态值为1,我会这样;

[10100004] => Array
        (
            [0] => stdClass Object
                (
                    [ID] => 1116
                    [barcode] => 10100004                   
                    [status] => 1
                )

            [1] => stdClass Object
                (
                    [ID] => 1826
                    [barcode] => 10100004                    
                    [status] => 0
                )

        )

我的代码在这里;

$result = array();
            foreach ($fetch_data as $value) {
              if($value->status== 1)
              $result[$value->barcode][] = $value;
            }

//这只给我一个结果。输出;

[10100004] => Array
        (
            [0] => stdClass Object
                (
                    [ID] => 1116
                    [barcode] => 10100004                   
                    [status] => 1
                )
)

1 个答案:

答案 0 :(得分:0)

您可以使用| NewCol | | ------- | | 1-ABC-9 | | ABC-1-9 | | 9-1-ABC | | ABC | | 1-100-9 |

array_walk

输出

$arr = Array(
 '10100002' => Array
 (
    '0' => Array
        (
            'ID' => 664,
            'barcode' => 10100002,                
            'status' => 0
        ),

    '1' => Array
        (
            'ID' => 1339,
            'barcode' => 10100002,                  
            'status' => 0
        )

 ),
'10100004' => Array
(
    '0' => Array
        (
            'ID' => 1116,
            'barcode' => 10100004,                  
            'status' => 1
        ),

    '1' => Array
        (
            'ID' => 1826,
            'barcode' => 10100004,                 
            'status' => 0
        )

)
);
$res = [];
array_walk($arr, function($v, $k) use (&$res){
  foreach($v as $key => $value){
    if($value['status']){
       !empty($value['status']) ? ($res[$k][] = (object)$v[$key]) : '';
     }
 }
});
echo '<pre>';
print_r($res);

LIVE DEMO