我有以下JSON格式:
$myresult = '{"promoter_name":[],"country":["Hong Kong"],"download":["Yes"],"download_date_range":["20161201","20161215"],"first_login_date_range":[],"last_login_date_range":[],"login_frequency":[]}'
我想使用PHP打印单个值,例如:
$download = 'Yes';
$country = "Hong Kong";
答案 0 :(得分:1)
$result = '{"promoter_name":[],"country":["Hong Kong"],"download":["Yes"],"download_date_range":["20161201","20161215"],"first_login_date_range":[],"last_login_date_range":[],"login_frequency":[]}';
$arr = json_decode($result,true);
$country = $arr['country'][0];
$download = $arr['download'][0];
这是数组方法。如果使用对象方法代码将是这样的;
$arr = json_decode($result);
$country = $arr->country[0];
$download = $arr->download[0];
或者您使用动态变量
foreach($arr as $k=>$v){
if($v != []){
${$k} = $v[0];
}
}
echo $country;
echo $download
答案 1 :(得分:0)
首先将字符串解码为
$arrResult = json_decode($result, true);
然后使用索引来访问值
答案 2 :(得分:0)
像这样使用json_decode
。 json_decode
将您的json转换为object,然后使用箭头操作符访问每个成员。
<?php
$result = '{"promoter_name":[],"country":["Hong Kong"],"download":["Yes"],"download_date_range":["20161201","20161215"],"first_login_date_range":[],"last_login_date_range":[],"login_frequency":[]}';
$res = json_decode($result);
echo $res->country[0];//and so on
?>
OR
<?php
$result = '{"promoter_name":[],"country":["Hong Kong"],"download":["Yes"],"download_date_range":["20161201","20161215"],"first_login_date_range":[],"last_login_date_range":[],"login_frequency":[]}';
$res = json_decode($result,true);
foreach($res as $key=>$value)
{
foreach($value as $k=>$v){
$data[$key] = $v;
}
}
extract($data);
echo $country;//outputs Hong Kong so on
?>
OR
<?php
$result = '{"promoter_name":[],"country":["Hong Kong"],"download":["Yes"],"download_date_range":["20161201","20161215"],"first_login_date_range":[],"last_login_date_range":[],"login_frequency":[]}';
$res = json_decode($result,true);
foreach($res as $key=>$value)
{
foreach($value as $k=>$v){
echo $key."='".$v."'<br/>";
}
}
?>
<强>输出:强>
country='Hong Kong'
download='Yes'
download_date_range='20161201'
download_date_range='20161215'
答案 3 :(得分:0)
JSON字符串中的所有值都是数组:
$json = '{"promoter_name":[],"country":["Hong Kong"],"download":["Yes"],"download_date_range":["20161201","20161215"],"first_login_date_range":[],"last_login_date_range":[],"login_frequency":[]}';
您可以执行以下操作:
extract(json_decode($json, true));
echo $country[0]; // Hong Kong
echo $download[0]; // Yes
echo $download_date_range[0]; // 20161201
echo $download_date_range[1]; // 20161215
或者您可以过滤掉单个值:
foreach(json_decode($json, true) as $key => $value){
if(is_array($value) && count($value) == 1){
$data[$key] = $value[0];
} elseif(empty($value)) {
$data[$key] = null;
} else {
$data[$key] = $value;
}
}
extract($data);
echo $country; // Hong Kong
echo $download; // Yes
echo $download_date_range[0]; // 20161201
echo $download_date_range[1]; // 20161215