简体   繁体   中英

How to create a customized array from json file

i am trying to create a customized array out of my json file. But every time i run this, nothing comes out. Why is the happening??

This is my 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"}]

This is my code

$json = file_get_contents("somefile");
$decarr = json_decode($json, TRUE);

print_r($decarr);

This is my current output from my decarr array:

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.

This is my code for how to create my own array.

$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);

But this is what i am getting right now.

Array ( [0] => ('', '', '') [1] => ('', '', '')....and beyond

As you can see, the selected values won't store in my values array. why is the happening?

The Address1 , City , and ZipCode properties are inside an object that is an item of the Addresses array.

Change

$newrec = $decarr[$x];  

To:

$newrec = $decarr[$x]['Addresses'][0];  

Or if you want, you could also add all addresses:

for ($y = 0; $y < count($decarr[$x]['Addresses']); $y++) {
    $newrec = $decarr[$x]['Addresses'][$y];

    ...

    $values[] = "('".$num."', '".$desc."', '".$freq."')";   
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM