0

我正在尝试从我的 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

如您所见,所选值不会存储在我的值数组中。为什么会这样?

4

1 回答 1

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."')";   
}
于 2013-08-22T22:26:54.060 回答