Saikios Saikios - 7 months ago 21
PHP Question

improving loop throw a schema on php

This is working, but feels really "dirty"

I have a schema json like:

[
{
"url": "http://www.google.com/api/updateVariable",
"verb": "POST",
"bodySchema": {
"type": "object",
"properties": {
"StoreId": {
"sync": "True",
"type": "integer"
},
"SKU": {
"sync": "True",
"type": "string"
},
"WareHouseId": {
"sync": "False",
"type": "integer"
},
"Stock": {
"sync": "True",
"type": "integer"
}
},
"required": [
"StoreId",
"SKU",
"Stock"
]
}
},

{
"url": "http://www.google.com/api/insertVariable",
"verb": "POST",
"bodySchema": {
"type": "object",
"properties": {
"StoreId": {
"sync": "True",
"type": "integer"
},
"SKU": {
"sync": "True",
"type": "string"
},
"WareHouseId": {
"sync": "False",
"type": "integer"
},
"Description": {
"sync": "True",
"type": "integer"
}
},
"required": [
"StoreId",
"SKU",
"Description"
]
}
}
]


And I want to loop throw all the properties (once again, this is working)

$result=json_decode($result, true);
while($item = array_shift($result)){
foreach ($item as $key => $value){
if($key=="bodySchema"){
foreach ($value as $key2 => $value3){
if($key2==properties)
var_dump($value3);
}
}
}
}


What I would like to have is something like:

$result=json_decode($result, true);
foreach($result as $mydata){
foreach($mydata->bodySchema->properties as $values){
var_dump($values->value);
}
}


is this possible?, I want to keep this code as clean and neat as possible

Answer

Yes, you can do it the way you want. You just have some syntax to cleanup to do.

In this example, $result is an associative array, so you can index into it just like any array.

$result = json_decode($result, true);
foreach ($result as $mydata) {
    foreach ($mydata["bodySchema"]["properties"] as $propertyName => $schema){
          var_dump([$propertyName, $schema]);
    }
}

If you prefer object syntax, drop the true from json_decode.

$result = json_decode($result);
foreach ($result as $mydata) {
    foreach ($mydata->bodySchema->properties as $propertyName => $schema){
          var_dump([$propertyName, $schema]);
    }
}