PHP - 过滤,保留多维数组上的任何键

时间:2016-02-16 09:07:43

标签: php arrays filter

我有一个数组(从模型返回):

$array = [
    [
        'id' => 1,
        'name' => 'Name 1',
        'date' => '2016'
        'other' => '...'
    ],
    [
        'id' => 2,
        'name' => 'Name 2',
        'date' => '2016'
        'other' => '...',
        'children' =>
            [
                'id' => 3,
                'name' => 'Name 3',
                'date' => '2016'
                'other' => '...',
                'children' =>
                    [
                        ....
                    ]
            ]
    ],
];

我想过滤此数组,只需保留密钥:idname& children,如:

$array = [
    [
        'id' => 1,
        'name' => 'Name 1'
    ],
    [
        'id' => 2,
        'name' => 'Name 2'
        'children' =>
            [
                'id' => 3,
                'name' => 'Name 3'
                'children' =>
                    [
                        ....
                    ]
            ]
    ],
];

我试图保留重要数据,删除不是'id','name'和&的键。 'children',然后将此数组转换为json。

请帮帮我!谢谢!

3 个答案:

答案 0 :(得分:1)

递归功能是你的朋友! 像这样:

public static void main(String[] args) {

    GenericTest genericTest = new GenericTest();

    genericTest.setValue(new BigDecimal("10"));
    genericTest.setValue(new Date(0));

}

public void setValue(BigDecimal element) {
    checkBigDecimal(element);
}

public void setValue(Date element) {
    checkDate(element);
}

public void checkDate(Date localDate) {
    System.out.println("This is Date metho, Caller has casted T to Date");
}

public void checkBigDecimal(BigDecimal localBigDecimal) {
    System.out.println("This is BigDecimal method, Caller has casted T to BigDecimal");
}

我还没有测试过,所以也许你需要做一些调试。

答案 1 :(得分:0)

试试这个:

  function minifyarray($item){
         $newitem = [
              'id' => $item['id'] , 
              'name' => $item['name']
         ];

         if(!empty($item['children']))
             $newitem['children'] = array_map('minifyarray', $item['children']);

         return $newitem;
    }

  $newarray = array_map('minifyarray', $array);

答案 2 :(得分:-1)

只需制作循环并取消不需要的东西

function recursivelyRemoveUnwantedStuff($input){
    if(array_key_exists('date',$input)){
          unset($input['date']);
    }

    if(array_key_exists('other',$input)){
          unset($input['other']);
    }

    if(array_key_exists('children',$input)){        
        $input['children'] = recursivelyRemoveUnwantedStuff($input['children']);
    }

    return $input;        
 }

然后

<?php outPutArray = recursivelyRemoveUnwantedStuff($inputArray); ?>