我想创建一个具有如下结构的json对象数组:
{
"client-mac": "0C:D2:B5:68:73:24",
"client-dbm": "-82",
"clientManuf": "unknown"
}
我正在使用以下php代码来获得此结果:
$clientMac = $clients->{'client-mac'};
$clientStrength = $clients->{'snr-info'}->{'last_signal_dbm'};
$clientManuf = $clients->{'client-manuf'};
$jsonObject = array('client-mac' => $clientMac,
'client-dbm' => $clientStrength,
'clientManuf' => $clientManuf);
$jsonString = json_encode($jsonObject);
问题是我正在关注json字符串:
{"client-mac":{
"0":"0C:D2:B5:68:73:24"
},
"client-dbm":{
"0":"-82"
},
"clientManuf":{"0":"Unknown"}
}
为什么我将这些额外的密钥设为“0”?我怎样才能得到我想要的输出?提前谢谢你:)
答案 0 :(得分:2)
显然,您的源数据还有一个嵌套级别,其中包含一个键/值对。
您可以使用reset
来从中选择第一个值:
array('client-mac' => reset($clientMac),
'client-dbm' => reset($clientStrength),
'clientManuf' => reset($clientManuf));
答案 1 :(得分:0)
这是因为$clientMac
,$clientStrength
和$clientManuf
是对象,而不是文字字符串。您必须按以下方式更改前三行,
$clientMac = $clients->{'client-mac'}->{'0'};
$clientStrength = $clients->{'snr-info'}->{'last_signal_dbm'}->{'0'};
$clientManuf = $clients->{'client-manuf'}->{'0'};
...