Get specific element from each sub array

后端 未结 2 841
旧时难觅i
旧时难觅i 2020-12-25 11:04

I have a common pattern which Im sure there must be a built-in array function in PHP to handle but just can\'t see it.

I have multiple arrays such as the following:<

2条回答
  •  天命终不由人
    2020-12-25 11:46

    As of PHP 5.5 you can use the array_column() function:

    $key = 'key1';
    
    $testArray = array (
        'subArray1' => array(
            'key1' => "Sub array 1 value 1",
            'key2' => "Sub array 1 value 2"
        ),
        'subArray2' => array(
            'key1' => "Sub array 2 value 1",
            'key2' => "Sub array 2 value 2"
        )
    );
    
    $output = array_column($testArray, $key);
    var_dump($output);
    

    Will output:

    array(2) {
      [0]=>
      string(19) "Sub array 1 value 1"
      [1]=>
      string(19) "Sub array 2 value 1"
    }
    

    The only difference with the accepted answer is that you lose the original key name, but I think this is not a problem in your case.

提交回复
热议问题