提问人:fitra 提问时间:3/29/2020 最后编辑:mariofitra 更新时间:3/29/2020 访问量:74
遍历未知的 JSON 键 [已关闭]
traversing unknown json keys [closed]
问:
我不知道如何像这样解析遍历数组数据
{
"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];
}
}
答:
2赞
The Codesee
3/29/2020
#1
试一试,让我知道它是否是你想要的:
//$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;
评论
0赞
fitra
3/29/2020
对不起,先生标签 foo-1、foo-2、foo-3 它的动态可以用其他名称更改
0赞
fitra
3/29/2020
非常感谢你@The Codesee 我用这个代码卡住了 3 天
0赞
The Codesee
3/29/2020
@fitra 因为你的数组是动态的,所以我对我的答案做了一些更改
评论