简体   繁体   中英

How to replace arrays of multidimensional array with items of that array using php?

In the multi-dimensional array below how would I replace the top level indices [0] [1] & [2] with their respective values from [SUB1]

Array
(
    [0] => Array
        (
            [SUB1] => AAA111
            [SUB2] => Description 1
            [SUB3] => 10
        )

    [1] => Array
        (
            [SUB1] => BBB222
            [SUB2] => Description 2
            [SUB3] => 20
        )

    [2] => Array
        (
            [SUB1] => CCC333
            [SUB2] => Description 3
            [SUB3] => 30
        )

)

I've managed to use $sub1 = array_column( $array, 'SUB1' ); to get the below array, but I'm not sure if a simple function exists to use it to replace the indices in the original array with the values.

Array
(
    [0] => AAA111
    [1] => BBB222
    [2] => CCC333
)

Edit:

Desired output:

Array
(
    [AAA111] => Array
        (
            [SUB2] => Description 1
            [SUB3] => 10
        )

    [BBB222] => Array
        (
            [SUB2] => Description 2
            [SUB3] => 20
        )

    [CCC333] => Array
        (
            [SUB2] => Description 3
            [SUB3] => 30
        )

)

Please check below example, Where $test is equal to your main array.

$output = [];
foreach ($test as $t) {
    $first = reset($t);
    $remaining = array_shift($t);
    $output[$first] = $t;
}

echo '<pre>';
print_r($output);

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