简体   繁体   中英

How to change multidimensional php array into simple associative array with values as keys?

Language is PHP .

So I want to turn a multidimensional array into a simple associative array that uses every second value as a key and every third value as a value to that key.

The initial array looks like this:

Array
(
[0] => Array
    (
        [id] => 1
        [name] => Adam
        [value] => 150
    ),

[1] => Array
    (
        [id] => 2
        [name] => Bob
        [value] => 120
    ),

[2] => Array
    (
        [id] => 3
        [name] => Charlie
        [value] => 175
    )

)

I want to turn it into a simple associative array that looks like this:

Array
(
Adam => 150,
Bob => 120,
Charlie => 175
)

I tried (and failed with) something like this:

$initialArray;
$arrayPrepped = array();
    foreach ($initialArray as $part) {
        foreach ($part as $name => $value) {
            if ($name == 'name') {
                $key = $value;
            } elseif ($name == 'value') {
                $finalvalue = $value;
            }
            $finalpart = array($key => $finalvalue);
        }
        array_merge($initialArray, $finalpart);
    }

What about this one-liner!

print_r(array_column($initialArray, 'value', 'name'));

Read up on array_column .

Your original value looks like:

$a = Array
(
    Array(
        'id' => 1,
        'name' => 'Adam',
        'value' => 150
    ),
    Array
    (
        'id' => 1,
        'name' => 'Job',
        'value' => 200
    ),

);

Then work on:

$myarr = [];
foreach ($a as $item) {
    $myarr[$item['name']] = $item['value'];
}
echo "<pre>";
print_r($myarr);

output:

Array
(
    [Adam] => 150
    [Job] => 200
)

You can go through array and setup value into new array in that way.

$initialArray = [
    0 => [
        'id'    => 1,
        'name'  => 'Adam',
        'value' => 150,
    ],

    1 => [
        'id'    => 2,
        'name'  => 'Bob',
        'value' => 120,
    ],

    2 => [
        'id'    => 3,
        'name'  => 'Charlie',
        'value' => 175,
    ],
];
$arrayPrepped = array();
foreach ($initialArray as $part) {
    $arrayPrepped[$part['name']] = $part['value'];
}

Here is example of execution

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM