遍历未知的json键

时间:2020-03-28 16:36:07

标签: php json arraylist

我不知道如何解析这样遍历数组数据

{
  "foo-1": [
    [
      A,
      3
    ],
    [
      B,
      3
    ]
  ],
  "foo-2": [
    [
      A,
      1
    ],
    [
      B,
      7
    ]
  ],
  "foo-3": [
    [
      A,
      1
    ],
    [
      B,
      6
    ]
  ]
}

我想要这样的结果

(foo-1,foo-2,foo-3)
(A,B)
(3,3)(1,7)(1,6)

我的代码

$data = file_get_contents("example/data");
$parsing = json_decode($data, true);

foreach($parsing as $row=>$val){
   $data1 .= $row; //success

   foreach($row as $rows){ // don't know how to parsing child data
    $data2 .= $rows[0];
    $data3 .= $rows[1];
    }
}

1 个答案:

答案 0 :(得分:2)

试试看,让我知道这是否是您想要的:

//$arrays = array("foo-1" => array(array("A", 3), array("B", 3)), "foo-2" => array(array("A", 1), array("B", 7)), "foo-3" => array(array("A", 1), array("B", 6)));

$data = file_get_contents("example/data"); // enter your link here
$arrays = json_decode($data, true);

$names = "(";
$letters = "(";
$numbers = "";
$coordinate = "";

foreach($arrays as $arrayName => $array) {
    if(array_search($arrayName, array_keys($arrays)) == 0) {
        $names .= $arrayName;
    }else{
        $names .= ",".$arrayName;
    }
    foreach($array as $key => $nestedArray) {
        foreach($nestedArray as $letterOrNum => $value) {
            if($letterOrNum == 0) { // it's a letter
                if($key + 1 == 1) {
                    $nextLetter = $array[$key + 1][0];
                    if (!strpos($letters, $value.','.$nextLetter) !== false) {
                        if($key == 0 && array_search($arrayName, array_keys($arrays)) == 0) {
                            $letters .= $value;
                        }else{
                        $letters .= ",".$value;
                        }
                    }
                }else{
                    $previousLetter = $array[$key - 1][0];
                    if (!strpos($letters, $previousLetter.','.$value) !== false) {
                        if($key == 0 && array_search($arrayName, array_keys($arrays)) == 0) {
                            $letters .= $value;
                        }else{
                        $letters .= ",".$value;
                        }
                    }
                }
            }else{ // its a number
                if($key == 0) {
                    $coordinate .= "(".$value.",";
                }else{
                    $coordinate .= $value.")";
                }
                $numbers .= $coordinate;
                $coordinate = "";
            }
        }
    }
}

$names .= ")";
$letters .= ")";

echo $names;
echo $letters;
echo $numbers;

演示:https://3v4l.org/mMoT6

相关问题