Slicing a multi-dimensional PHP array across one of its elements

后端 未结 10 866
再見小時候
再見小時候 2020-12-28 15:51

Say for example you just queried a database and you recieved this 2D array.

$results = array(
    array(\'id\' => 1, \'name\' => \'red\'  , \'spin\' =&         


        
相关标签:
10条回答
  • 2020-12-28 16:24

    You could do:

    $tmp = array_flip($names);
    $names = array_keys($tmp);
    
    0 讨论(0)
  • 2020-12-28 16:26

    If you are running a version of PHP before 5.5 and array_column(), you can use the official replacement in plain PHP:

    https://github.com/ramsey/array_column

    0 讨论(0)
  • 2020-12-28 16:28

    As of June 20th in PHP-5.5 there is a new function array_column

    For example:

    $records = array(
        array(
            'id' => 2135,
            'first_name' => 'John',
            'last_name' => 'Doe'
        ),
        array(
            'id' => 3245,
            'first_name' => 'Sally',
            'last_name' => 'Smith'
        ),
        array(
            'id' => 5342,
            'first_name' => 'Jane',
            'last_name' => 'Jones'
        ),
        array(
            'id' => 5623,
            'first_name' => 'Peter',
            'last_name' => 'Doe'
        )
    );
    
    
    $firstNames = array_column($records, 'first_name');
    print_r($firstNames);
    

    Will return

    Array
    (
        [0] => John
        [1] => Sally
        [2] => Jane
        [3] => Peter
    )
    

    There are even more examples in the above mentioned link.

    0 讨论(0)
  • 2020-12-28 16:28

    Starting PHP 5.3, you can use this pretty call with lambda function:

    $names = array_map(function ($v){ return $v['name']; }, $results);
    

    This will return array sliced by 'name' dimension.

    0 讨论(0)
  • 2020-12-28 16:35

    I did more research on this and found that ruby and prototype both have a function that does this called array_pluck,2. It's interesting that array_map has a second use that allows you to do the inverse of what i want to do here. I also found a PHP class someone is writing to emulate prototypes manipulation of arrays.

    I'm going to do some more digging around and if I don't find anything else I'll work on a patch to submit to the internals@lists.php.net mailing list and see if they will add array_pluck.

    0 讨论(0)
  • 2020-12-28 16:37

    For those of you that cannot upgrade to PHP5.5 right now and need this function, here is an implementation of array_column.

    function array_column($array, $column){
        $a2 = array();
        array_map(function ($a1) use ($column, &$a2){
            array_push($a2, $a1[$column]);
        }, $array);
        return $a2;
    }
    
    0 讨论(0)
提交回复
热议问题