如何从json文件创建自定义数组


How to create a customized array from json file

我正试图用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

正如您所看到的,所选的值不会存储在我的值数组中。为什么会发生这种事?

Address1CityZipCode属性位于作为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."')";   
}