phparraysloopsforeachassociative

how can I restructure an associative array using a PHP foreach loop (or not)?


so here is the first key of an associative array named $results:

[
    10 (2) => [
        step (3) => [
            0 (1) => [
                id => 1
            ],
            1 (1) => [
                id => 2
            ],
            2 (1) => [
                id => 3
            ]
        ],
        status (3) => [
            0 (1) => [
                id => 2
            ],
            1 (1) => [
                id => 4
            ],
            2 (1) => [
                id => 10
            ]
        ]
    ],

I'd like to resructure it to make it look like this:

[
    10 (2) => [
        step (1) => [
            0 (1) => [
                id => 1
            ],
        status (1) =>[
            0 (1) => [
                id => 2
            ],
        step (1) => [
            0 (1) => [
                id => 2
            ],
        status (1) =>[
            0 (1) => [
                id => 4
            ],
            
          AND SO ON...
           

to put it in a nutshell I just want to display step & status as a pair for each step and result in an [step, status], [step, status], [step, status]... associative array. For now thhe array is more like [step, step step], [status, status, status].

Here is my initial foreach loop that gave me the array in the first place :

$results = [];

        foreach ($entities['node'] as $nodeIdBis => $nodeWkf) {

            $nodeWkfTmp = ["step" => [], "status" => []];
            
            foreach ($nodeWkf as $wkfId => $subNodeWkf) {

                foreach ($subNodeWkf as $stepId => $nodeStatus) {

                    $nodeWkfTmp["status"][] = ["id" => $nodeStatus['statusId']];
                    $nodeWkfTmp["step"][]  = ["id" => $stepId];
                }
            }
            $results[$nodeIdBis] = $nodeWkfTmp;
        }

much respect for who will find the trick :)


Solution

  • Just change the $nodeWkfTmp array assignment to get an array of pairs [step, status]:

    $nodeWkfTmp = [];
    
    $nodeWkfTmp[] = [
      "status" => ["id" => $nodeStatus['statusId']],
      "step"   => ["id" => $stepId]
    ];