如何删除基于键的数组列表?

时间:2019-05-15 08:43:38

标签: php arrays json codeigniter

例如:

Array   
(    
[0] => Array 
 (
     [id] => 23
     [merchant_id] => 23   
 )
[1] => Array 
 (
     [id] => 24
     [merchant_id] => 46  
 )
)

我要在操作后删除除46以外的商人ID的列表:

Array   
    (    
    [0] => Array 
     (
         [id] => 24
         [merchant_id] => 46  
     )
    )

如何删除此数组列表的最佳方法?

3 个答案:

答案 0 :(得分:3)

您可以按照以下步骤使用array_filter来获得结果

// suppose your data is in $data variable
$data = [
  ['id' => 23,
     'merchant_id' => 23],

  ['id' => 23,
     'merchant_id' => 46],

 ];

//return true only if marchant_id == 46 
$filtered_array = array_filter($data,function($datum){
                     return $datum["merchant_id"] == 46;
                  });

答案 1 :(得分:2)

嗨,请检查下面的代码

Tag

答案 2 :(得分:0)

如果您在数组函数中苦苦挣扎,那么简单的foreach循环和对您感兴趣的字段的测试会很好地完成

$A = [  ['id' => 23, 'merchant_id' => 23  ],
        ['id' => 24, 'merchant_id' => 46  ],
        ['id' => 25, 'merchant_id' => 21  ],
        ['id' => 26, 'merchant_id' => 29  ],
    ];


foreach ( $A as $key => $t ) {
    if( $t['merchant_id'] != 46 ){
        unset($A[$key]);
    }
}

print_r($A);

结果

Array
(
    [1] => Array
        (
            [id] => 24
            [merchant_id] => 46
        )

)