如何获得此脚本的良好输出: 来源JSON:https://ufile.io/sn0hu
我需要将值输入数组,然后在下一步中使用变量。 值为result-> data-> tab-> unified_content-> item(如果header = title,则为type-> text,如果text = description)
脚本:
function getContent($data) {
$tabs = $data->result->data->tab;
foreach($tabs as $tab){
$content = [];
if(isset($tab->unified_content->item)) {
foreach($tab->unified_content->item as $item) {
if($item->type->name == 'header') {
$arr = [];
$arr['title'] = $item->text;
} else {
$arr['description'] = $item->text;
$content[] = $arr;
}
}
return $content;
}
}
}
$test = getContent($data);
foreach ($test as $lol) {
var_dump($lol);
}
现在输出:array(1){[" description"] => string(0)"" }
答案 0 :(得分:2)
您需要在$content
循环之前初始化foreach
,然后将其返回。否则,您只返回unified_content->item
存在的第一个标签中的内容。该选项卡只包含一个项目,没有标题和空文本。:
"item": [{
"id": 17229,
"text": "",
"align": "l",
"type": {
"id": 3,
"name": "image"
},
"width": "l",
"shape": "s",
"swajp": 0,
"icon": 273,
"margin": 1,
"image": [{
"id": 10482,
"src": "image.php?id=18432&app_id=5786&key=a1bd33754a582bc1094e5f1b170adbb4747b7bdb",
"title": "V ned\u011bli 12.11. od 14:00 hrajeme v Bra\u0161kov\u011b",
"width": 1920,
"height": 1345
}, {
"id": 10480,
"src": "image.php?id=18430&app_id=5786&key=62d75ca8ea4c16fdd6a4bec8c48848f692b843bf",
"title": "Dom\u00e1c\u00ed prohra na penalty s Jedom\u011blicemi 2:3 (1:2) Pen: 2:4",
"width": 1920,
"height": 1218
}, {
"id": 10483,
"src": "image.php?id=18433&app_id=5786&key=1e1479dcf8de55f57e29e1a16f428f4414c76032",
"title": "Unho\u0161\u0165 spadla na 11. m\u00edsto v tabulce",
"width": 1920,
"height": 1280
}, {
"id": 49465,
"src": "image.php?id=90502&app_id=5786&key=3103a185854b771cdad784950d343bb3e143bec6",
"title": "\u00dasp\u011b\u0161n\u00fd fotbalov\u00fd kemp",
"width": 1000,
"height": 750
}]
}]
您还应该在内部循环之前初始化$arr
,而不是if
,以防没有header
对象。
function getContent($data) {
$tabs = $data->result->data->tab;
$content = [];
foreach($tabs as $tab){
if(isset($tab->unified_content->item)) {
$arr = [];
foreach($tab->unified_content->item as $item) {
if($item->type->name == 'header') {
$arr['title'] = $item->text;
} else {
$arr['description'] = $item->text;
$content[] = $arr;
}
}
}
}
return $content;
}
答案 1 :(得分:1)
下次请说清楚你在寻找什么(什么是"好的输出"?)。
使用json_decode($ json_file,true)。 即:
<?php
$json_file = file_get_contents("testing.json");
$json_decode = json_decode($json_file, true); //Sets it as an array
print_r($json_decode['result']['status']); //Will print out "done" in this case
?>
同样,这可能不是您正在寻找的答案,因为它并不清楚您在OP中寻找的是什么。