0

I have some project where I get from external API big dimension array. This api return JSON in many dimensions. I have to do many operations of this data so I want to change/convert this nested array to my object class, not StdObject. I looking long time the best way for that and I try two solutions:

  1. I write hydrator which convert me dimensions array to my Entity object. But when is many diffrent type data in this array is hydrator code not so good.
  2. Another way is some loop and serialize each level array to own many Entity class. And final somehow merge to one object

Below put example many dimension array:

$arr = [
    'geometry' =>
        [
            'location' => ['lat' => 54.352095, 'lng' => 18.650461],
            'viewport' => ['northeast' => ['lat' => 54.35213084999999, 'lng' => 18.65059885], 'southwest' => ['lat' => 54.35206664999999, 'lng' => 18.65041305],],
        ],
    'icon' => 'https://maps.gstatic.com/mapfiles/place_api/icons/generic_business-71.png',
    'id' => '2a293ddb8ddfdc1d65274d12c8465e50a3fe68ef',
    'name' => 'Cafe Szafa',
    'opening_hours' => [
        'open_now' => false, 
        'weekday_text' => [
            'text1',
            'text2',
        ]
    ],
    'photos' => [
        'number' => 6,
        'quality' => 90
    ],
    'place_id' => 'ChIJkaVEf3Vz_UYRQdJXi93rMuo',
    'rating' => 4.2,
    'reference' => 'CmRSAAAAUh4a5IzCSVbJTewsfTI0t-rBLC-SwY417eXejcn9GN4el36oLMCSlPKukX6BCiQRV8SU1WmtptK5vx3VsLYZSVxmYmG0eyz87tQk9qO7fPgGcuThczRu4-g4KVSCWDUeEhBxTHb4lNKjk9_qveBXVh1NGhSLW4uY08XRCJFv8ivPK1j-EP8hnw',
    'scope' => 'GOOGLE',
    'types' => ['bar', 'point_of_interest', 'establishment'],
    'vicinity' => 'Podmurze 2, Gdańsk',
];

Finale I want get one object my own class with data from this array but I don't all data from array "put" to mam propetris object only some, selected. And I wan't get object StdObject. Maybe you know better way to to that I found only describe in point 1 and 2. I will be grateful for any tips and help

Marcin
  • 1
  • 1
  • "put" to mam propetris object only some, selected.? can't understand what you are asking if you want to array object means you can use `json_encode();` – Nawin Mar 09 '18 at 07:58
  • Basically if the structure of the object is well known you can just have a class constructor that initializes class properties with this array. Each sub-array can call a constructor on another class. – apokryfos Mar 09 '18 at 07:59
  • You should take a look at https://jmsyst.com/libs/serializer and its deserialization capabilities – Noémi Salaün Mar 09 '18 at 08:20
  • `print_r(json_encode($arr, JSON_FORCE_OBJECT));` Will do this trick... – Nawin Mar 09 '18 at 11:31

1 Answers1

0
  1. you need to encode it as json
  2. decode the result with the second params to true

     $object= json_decode(json_encode($arr),true);
    
cute_programmer
  • 332
  • 3
  • 13