user10859447
user10859447

Reputation: 3

PHP Array rearrange numeric key as parrent key

i want to rearrange a simple multidimensional array.

Array
    (
        [pieces] => Array
            (
                [0] => 2
                [1] => 9
            )
        [start] => Array
            (
                [0] => 0001
                [1] => 9901
            )
        [end] => Array
            (
                [0] => 0002
                [1] => 9909
            )
        [group] => Array
            (
                [0] => 0001-0100
                [1] => 9901-9999
            )
    )

to

Array
(
    [tokens] => Array
        (
            [0] =>  Array
                (
                    [start] => 0001
                    [end] => 0002
                    [pieces] => 2
                    [group] => 0100
                )
            [1] =>  Array
                (
                    [start] => 9901
                    [end] => 9909
                    [pieces] => 9
                    [group] => 9901-9999
                )
        )
)

I have tried something similar this:

$keys = array_keys($array);
foreach ($keys as $key => $val) {       
    foreach ($array as $k => $v){
        foreach($array[$v] as $tk => $tv){
            if($val == $k){
                $new['tokens'][][$val] = $tv;
            }
        }
    }
}

The numeric is the set of tokens which i prosted from my form,

Please can anyone explain me what i do wrong? I am working some hours with different codes (i know the solution is very simple) but I am a little bit confused :/

Thank you very much!

BR KK

Upvotes: 0

Views: 47

Answers (1)

Sammitch
Sammitch

Reputation: 32242

The Fourth Bird's solution is quite rigid in that it:

  • Requires an explicitly-defined key in the loop condition.
  • Enforces that the entire result has no more items than that one key has.
  • Assumes and enforces that the input keys are sequential and zero-indexed.

The below will work no matter what:

foreach( $array as $y => $inner ) {
    foreach( $inner as $x => $value ) {
        $new['tokens'][$x][$y] = $value;
    }
}

Demo: https://3v4l.org/Rmdtd


Edit: I think it's worth preserving The Fourth Bird's explanation of the trouble with the posted code from his now-deleted answer:

You are trying to index into $array[$v], but $v in the case is one of the sub arrays. According to the array docs:

Arrays and objects can not be used as keys. Doing so will result in a warning: Illegal offset type.

Make sure that you have error_reporting turned up to E_ALL while you're developing code so that you can see non-critical messages that indicate current and/or future problems.

Upvotes: 3

Related Questions