我正在尝试从我的json文件中创建一个自定义数组。但每次我这样做,什么都没有出来。为什么会发生?
这是我的JSON:
[{"Account":null,"Addresses":[{"Address1":"Store Kongensgade 72","City":"K\u00d8BENHAVN K","CoAddress":null,"Country":{"AttributeBag":null,"Code":"DK","Text":"Danmark"},"Type":{"AttributeBag":null,"Code":"Postal","Text":"Postadress"},"ZipCode":"1264"}]
这是我的代码
$json = file_get_contents("somefile");
$decarr = json_decode($json, TRUE);
print_r($decarr);
这是我的decarr数组的当前输出:
Array ( [0] => Array ( [Account] => [Addresses] => Array ( [0] => Array ( [Address1] => Store Kongensgade 72 [City] => KØBENHAVN K [CoAddress] => [Country] => Array ( [AttributeBag] => [Code] => DK [Text] => Danmark ) [Type] => Array ( [AttributeBag] => [Code] => Postal [Text] => Postadress ) [ZipCode] => 1264 ) ) .....there is much more, but i had to stripped down.
这是我如何创建自己的数组的代码。
$count = count($decarr);
$values = array();
$update_values = array();
for ($x=0; $x < $count; $x++)
{
$newrec = $decarr[$x];
$num = $newrec['Address1']; $num = mysql_real_escape_string($num);
$desc = $newrec['City']; $desc = mysql_real_escape_string($desc);
$freq = $newrec['ZipCode']; $freq = mysql_real_escape_string($freq);
$values[] = "('".$num."', '".$desc."', '".$freq."')";
}
print_r($values);
但这就是我现在所得到的。
Array ( [0] => ('', '', '') [1] => ('', '', '')....and beyond
如您所见,所选值不会存储在我的values数组中。为什么会发生?
答案 0 :(得分:0)
Address1
,City
和ZipCode
属性位于作为Addresses
数组项目的对象内。
更改
$newrec = $decarr[$x];
要:
$newrec = $decarr[$x]['Addresses'][0];
或者如果您愿意,您还可以添加所有地址:
for ($y = 0; $y < count($decarr[$x]['Addresses']); $y++) {
$newrec = $decarr[$x]['Addresses'][$y];
...
$values[] = "('".$num."', '".$desc."', '".$freq."')";
}