Search code examples
phparraysmultidimensional-array

Remove array column and use it as the first level keys


I have a problem to rearrange the array. This is my final array:

Array
(
    [5833261e-dc14-48e3-9ee1-682a7f000201] => Array
        (
            [344] => apple - 344
            [345] => apple - 345
            [acc_name] => Apple 1233 - acc_name
        )

    [58332069-fab4-44c7-9ac9-487b7f000201] => Array
        (
            [343] => apple 123456 - 343
            [acc_name] => Orange Test - acc_name
        )
)

I want to rearrange this to like below:

Array
    (
        [Apple 1233 - acc_name] => Array
            (
                [344] => apple - 344
                [345] => apple - 345
            )
    
        [Orange Test - acc_name] => Array
            (
                [343] => apple 123456 - 343                
            )
    )

Can you please achieve this output array?


Solution

  • You can do it like below:

    $new_array = array();
    foreach ($array as $key => $val) {
        $acc_name = $val['acc_name'];
        unset($array[$key]['acc_name']);
        $new_array[$acc_name] = $array[$key];
    }
    echo "<pre/>";
    print_r($new_array);
    

    Note:- After completion you can assign this new array to your original array like $array = $new_array

    As per comments do one thing:-

    $new_array = array();
    foreach ($array as $key => $val) {
        $acc_name = $val['acc_name'];
        unset($array[$key]['acc_name']);
        $new_array[$acc_name][] = $array[$key];
    }
    echo "<pre/>";
    print_r($new_array);
    

    Note:- In array if same indexes are coming the the new data replaced the older-one. So try the second solution