PHP Store Key Value from Associative Array into Simple Array

后端 未结 5 2043
半阙折子戏
半阙折子戏 2021-01-21 07:57

I\'m having trouble wrapping my head around this, any help would be GREAT...

I have an array $stores that is structured like so:

Array
(         


        
5条回答
  •  盖世英雄少女心
    2021-01-21 08:16

    You can simply use the following syntax if you are unable to upgrade the php version. In that kind of case use if (!function_exists('array_column')) to prevent re-declaration of the function which may occur on version upgrade.

    Description From php.net

    array_column() returns the values from a single column of the array, identified by the column_key. Optionally, you may provide an index_key to index the values in the returned array by the values from the index_key column in the input array.

    /* Function array_column equivalent to php's array_column */
    if (!function_exists('array_column'))
    {
    
        function array_column(array $array, $column_key, $index_key = NULL)
        {
            if (isset($array))
            {
                $return = array();
                foreach ($array as $a)
                {
                    if ($index_key)
                    {
                        if (!isset($a[$index_key]))
                        {
                            return array();
                        }
                        else
                        {
                            $return[$a[$index_key]] = $a[$column_key];
                        }
                    }
                    else
                    {
                        $return[] = $a[$column_key];
                    }
                }
                return $return;
            }
            return array();
        }
    }
    

    Here are some examples taken from PHP.NET

     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',
        )
    );
    
    $first_names = array_column($records, 'first_name');
    print_r($first_names);
    ?>
    

    It will give below output:

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

    Get column of last names from recordset, indexed by the "id" column

    
    

    It will give you output as below:

    Array
    (
        [2135] => Doe
        [3245] => Smith
        [5342] => Jones
        [5623] => Doe
    )
    

提交回复
热议问题