Search code examples
phparrays

Remove first column from each row of a 2d array and apply values as first level keys


I'm trying to restructure an array but can't figure out how to rearrange it to output the id as the key, I want to change this:

Array
(
    [0] => Array
        (
            [0] => 16
            [1] => News
            [2] => News
            [3] => News
            [4] => News content
        )

    [1] => Array
        (
            [0] => 17
            [1] => about-us
            [2] => About us
            [3] => About us
            [4] => About us content

        )

)

To this:

Array
(
    [16] => Array
        (
            [0] => News
            [1] => News
            [2] => News
            [3] => News content
        )

    [17] => Array
        (
            [0] => about-us
            [1] => About us
            [2] => About us
            [3] => About us content

        )

)

Solution

  • I created this demo script. This should work.

    <?php
    
    $original = array(0 => array(16, 'News', 'Etc'), 1 => array(35, 'Be', 'Here'));
    
    foreach($original as $key => $value) {
      $new = array_shift($value);
      $newarray[$new] = $value;
    }
    
    echo '<pre>'.print_r($original,1).'</pre>';
    echo '<pre>'.print_r($newarray,1).'</pre>';
    ?>
    

    Output:

    Array
    (
    [0] => Array
        (
            [0] => 16
            [1] => News
            [2] => Etc
        )
    
    [1] => Array
        (
            [0] => 35
            [1] => Be
            [2] => Here
        )
    
    )
    
    Array
    (
    [16] => Array
        (
            [0] => News
            [1] => Etc
        )
    
    [35] => Array
        (
            [0] => Be
            [1] => Here
        )
    
    )