0

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
        )

)
4
  • Just create a new array in a simple loop … Commented Feb 24, 2017 at 11:58
  • 1
    Show the expected output. How do you want? Commented Feb 24, 2017 at 11:59
  • CBroe, I considered that, however I wasn't sure what the performance implications would be with a large data set. Commented Feb 24, 2017 at 12:26
  • Nithyanandhan M, good point, added to question. Commented Feb 24, 2017 at 12:29

1 Answer 1

2

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);
Sign up to request clarification or add additional context in comments.

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.