Get the innermost array of multidimensional array

2

I have the following json

{
  "data": {
    "card": {
      "current_phase": {
        "id": "3134719",
        "name": "Phase Final"
      },
      "child_relations": [
        {
          "cards": [
            {
              "id": "6405893",
              "current_phase": {
                "id": "3147728",
                "name": "Concluído 2"
              },
              "child_relations": [
                {
                  "pipe": {
                    "id": "458138"
                  },
                  "name": "Pipe 3 Conexão",
                  "cards": [
                    {
                      "id": "6407049",
                      "current_phase": {
                        "id": "3151152",
                        "name": "pipe 3 phase 1"
                      }
                    }
                  ]
                }
              ]
            }
          ]
        }
      ]
    }
  }
}

I need to always get the innermost array (what's inside), in this case it would be:

"current_phase": {
   "id": "3151152",
   "name": "pipe 3 phase 1"
}

I've tried several things, like the end function etc, the next thing I got was this with array_column:

  $resultarray = json_decode($response, true);
  // print_r($resultarray);
  $current_phase = array_column($resultarray['data'], 'current_phase');
  print_r($current_phase);
  die();
  /* 

  Array
  (
    [0] => Array
    (
      [id] => 3134719
      [name] => Phase Final
    )
  )

  */

- Using array_walk_recursive was the closest I got to what I needed:

array_walk_recursive($resultarray, function($item, $key) {
    echo "$key holds $item\n";
  });

Return:

    title holds 9YEOCC
id holds 3134719
name holds Phase Final
name holds Pipe 2 Conexao
id holds 6405893
id holds 3147728
name holds Concluído 2
id holds 458138
name holds Pipe 3 Conexão
id holds 6407049
id holds 3151152
name holds pipe 3 phase 1
    
asked by anonymous 08.05.2018 / 15:50

1 answer

2

Try this code ( variable $ json should contain your literal string as per your post ):

$nivel = 0;
$nivelMax = 0;
$posLim = 0;
for ($i = 0; $i < strlen ($json); $i++) {
    $car = substr($json, $i, 1);
    if ($car == '{') {
        $nivel++;
        if ($nivel > $nivelMax) {
            $nivelMax = $nivel;
            $posIniNivelMax = $i;
        }
    }
    if ($car == '}') {
        if ($nivel == $nivelMax)
            $posFimNivelMax = $i;
        $nivel--;
    }
    if ($car == ',') {
        $posLimAnt = $posLim;
        $posLim = $i;
    }
};
echo substr($json, $posLimAnt+1, $posFimNivelMax - $posLimAnt + 1) . '<br>';

It will show:

 "current_phase": {
    "id": "3151152",
     "name": "pipe 3 phase 1"
 }

Also check out the Ideone.com

09.05.2018 / 04:33