Task: There is a JSON file of this type:

{ "Postcode": 246050, "Region": "ГОМЕЛЬСКАЯ", "Area": "ГОМЕЛЬСКИЙ", "TownType": "Г", "TownName": "ГОМЕЛЬ", "StreetType": "УЛ", "StreetName": "БИЛЕЦКОГО", "Buildings": "4,5" }, { "Postcode": 246050, "Region": "ГОМЕЛЬСКАЯ", "Area": "ГОМЕЛЬСКИЙ", "TownType": "Г", "TownName": "ГОМЕЛЬ", "StreetType": "УЛ", "StreetName": "ВОЛОТОВСКАЯ", "Buildings": "2,2Г" }, 

It must be converted to another JSON so that the "Buildings" parameter is 1 value each. Those. like this:

 { "Postcode": 246050, "Region": "ГОМЕЛЬСКАЯ", "Area": "ГОМЕЛЬСКИЙ", "TownType": "Г", "TownName": "ГОМЕЛЬ", "StreetType": "УЛ", "StreetName": "БИЛЕЦКОГО", "Buildings": "4" }, { "Postcode": 246050, "Region": "ГОМЕЛЬСКАЯ", "Area": "ГОМЕЛЬСКИЙ", "TownType": "Г", "TownName": "ГОМЕЛЬ", "StreetType": "УЛ", "StreetName": "БИЛЕЦКОГО", "Buildings": "5" }, { "Postcode": 246050, "Region": "ГОМЕЛЬСКАЯ", "Area": "ГОМЕЛЬСКИЙ", "TownType": "Г", "TownName": "ГОМЕЛЬ", "StreetType": "УЛ", "StreetName": "ВОЛОТОВСКАЯ", "Buildings": "2" }, { "Postcode": 246050, "Region": "ГОМЕЛЬСКАЯ", "Area": "ГОМЕЛЬСКИЙ", "TownType": "Г", "TownName": "ГОМЕЛЬ", "StreetType": "УЛ", "StreetName": "ВОЛОТОВСКАЯ", "Buildings": "2Г" }, 

I wrote this code here:

 $d1 = file_get_contents('1.json'); $js1 = json_decode($d1); $js2= array(); $I = count($js1); $s=0; for ($i=0; $i<$I; $i++){ $par = explode(",", $js1[$i]->Buildings); $J = count($par); for ($j=0; $j<$J; $j++){ array_push($js2, $js1[$i]); $js2[$s]->Buildings=$par[$j]; $s++; } } 

But why he breaks json as it should, but in the Buildings parameter writes only the last value from the string. Although if in a loop after $ s ++ ask

  echo $par[$j]; echo "<br/>"; 

then it will show everything right, as it should go. But in the new array does not want to set different parameters.

    1 answer 1

    Everything is very simple. This is OOP. You assign an array cell, not a primitive type, but an object. In your case, it turns out that you assigned the same object to different cells of the array, to which you change the Building value, respectively, it changes in both cells. Just a solution for you.

      array_push($js2, clone($js1[$i])); 
    • Works great! But I did not understand my mistake ... Could you describe in more detail where she was? - Wlad
    • there are generally primitive types and object types, for example in Java int and Integer. if you make an assignment of a primitive type, then its value is assigned; if you assign an object type, then a reference to this object is assigned. and since you assigned the link in $ js2 [0] and $ js [1] to the same object, the object itself will be updated upon change. because of this, you need to duplicate the entire object in order to assign different values; don't forget to note that the question is answered - Kirill Staruhin
    • thank! now it became clearer! - Wlad