2

So I have a multidimensional array:

    Array
    (
        [0] => Array
            (
                [User_ID] => 1
                [Username] => A NAME
            )

        [1] => Array
            (
                [User_ID] => 2
                [Username] => ANOTHER NAME
            )
    )

I have seen how to flatten it...but say I want to do that and make it like so:

    Array
   (
       [1(As in the User_ID value)] => A NAME
       [2] => ANOTHER NAME
   )

Essentially creating a single array with the User_ID as the key and the Username as the value. How would I go about doing something like that? If it helps the list of IDs and Names could potentially be hundreds long, so it isn't a static number of items I am working with.

2 Answers 2

3

If you have PHP 5.5+, then there is actually a built-in function that can do this! It's called array_column.

$newArray = array_column($yourArray, 'Username', 'User_ID');

DEMO: https://eval.in/182109

If you have a version of PHP lower than 5.5, then you can include this in your code to shim array_column in: https://github.com/ramsey/array_column

Sign up to request clarification or add additional context in comments.

4 Comments

Sweet. Now why didn't they think of that earlier? ;)
@Fred-ii-: Because they wanted you to use a crazy mishmash of array_map and array_combine (or just a foreach) :-D
Their crazy little minds are constantly at work ;) Giving us better functions to work with later on, while eagerly waiting this happens (while) sipping Espressos and eating danishes at our favorite Café/Bistro.
I guess I don't have PHP5.5, but the little shim you provided worked. I will keep the array_column in mind for the future. Thank you.
3

For PHP versions < 5.5 or lacking the shim described by Rocket Hazmat, this will convert your array in to the necessary format:

<?php
$originalArray= array(
    0 => array(
        'User_ID' => 1,
        'Username' => 'A NAME'
    ),
    1 => array(
        'User_ID' => 2,
        'Username' => 'ANOTHER NAME'
    )
);

$newArray = array();
foreach ($originalArray as $element)
{
    $newArray[$element['User_ID']] = $element['Username'];
}
?>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.