首页 > 解决方案 > 从PHP(Laravel)中另一个数组中的数组中删除一些键

问题描述

如何从 PHP 中另一个数组中的数组中删除一些键?我有这个结构:

array (
  0 => 
  array (
    'num' => '123',
    'nome' => 'test 001'
    'pontos' => 68,
    'data_status' => '03/09/2021 10:05',
    'uuid_status' => '69450ea451ae11ea85ca309c23d3a0ed'
  ),
  1 => 
  array (
    'num' => '345',
    'nome' => 'test 002'
    'pontos' => 120,
    'data_status' => '27/08/2021 15:46',
    'uuid_status' => '3cbf4fd15d5411ea86956eef5d66cb13',
  ),
)

并且需要返回如下内容:

array (
  0 => 
  array (
    'num' => '123',
    'nome' => 'test 001'
    'pontos' => 68
  ),
  1 => 
  array (
    'num' => '345',
    'nome' => 'test 002'
    'pontos' => 120
  )
)

我已经看到了一些答案,但它们似乎已经过时了,我也在使用 Laravel,所以如果有人从框架中指出我的一些东西以及它在纯 PHP 中的等价物,那将会有所帮助

标签: phparrayslaravel

解决方案


一个简单的 foreach 循环是一个很好的起点,注意这将通过使用对&数组的引用而不是普通的简单副本从原始数组中删除项目。在$valforeach ( $input as &$val){

$input = [
    [   
        'num' => '123',
        'nome' => 'test 001',
        'pontos' => 68,
        'data_status' => '03/09/2021 10:05',
        'uuid_status' => '69450ea451ae11ea85ca309c23d3a0ed'
    ],[
        'num' => '345',
        'nome' => 'test 002',
        'pontos' => 120,
        'data_status' => '27/08/2021 15:46',
        'uuid_status' => '3cbf4fd15d5411ea86956eef5d66cb13'
    ]
];

$remove = ['data_status','uuid_status'];

foreach ( $input as &$val){
    foreach ($val as $k => $v) {
        if ( in_array($k,$remove) ) {
            unset( $val[$k]);
        }
    }
}
print_r($input);

结果

Array
(
    [0] => Array
        (
            [num] => 123
            [nome] => test 001
            [pontos] => 68
        )

    [1] => Array
        (
            [num] => 345
            [nome] => test 002
            [pontos] => 120
        )

)

推荐阅读