0

I send JSON object to server. On server side I have to parse this obj with PHP.

I'm stuck in the loop. I don't know how to proceed inside loops.

Im looking for most efficient way to parse this object and save all variables into DB.

[
{"ADI":{"id":-1,"danger":0}},
{"ADI":{"id":3,"danger":0}},
{"ADI":{"id":3,"danger":0}},
{"ALE":{"_id":1,"_name":"Milk","contain":false}},
{"ALE":{"_id":2,"_name":"cfg","contain":false}},
{"ALE":{"_id":4,"_name":"Lakt","contain":false}},
{"PRO":{"image":"","code":"123456","name":"jfbj"}},
{"USER":{"email":"[email protected]"}}
]

For now I have done this:

$string = file_get_contents('php://input');

$array = json_decode($string, true);
//print_r($array);

foreach ($array as $t => $index) {
   foreach ($index as $vas => $r) {
     //Here I'm stuck!!!
   }
}
6
  • 1
    Are you looking for an alternative to json_decode()? Why? Commented Nov 28, 2013 at 13:28
  • Seems you're going right...What exact problem you facing ? Commented Nov 28, 2013 at 13:29
  • What exactly are you trying to achieve? And where are you stuck? Commented Nov 28, 2013 at 13:29
  • 1
    I think you can try var_dump() it will show you where you "are" in the variable Commented Nov 28, 2013 at 13:32
  • 1
    In loops you write more code with relation to the value ($r) and the key ($vas). For example you run an SQL insert with that data. Commented Nov 28, 2013 at 13:40

2 Answers 2

1

you can grab values from json

<?php
$string = '[
{"ADI":{"id":-1,"danger":0}},
{"ADI":{"id":3,"danger":0}},
{"ADI":{"id":3,"danger":0}},
{"ALE":{"_id":1,"_name":"Milk","contain":false}},
{"ALE":{"_id":2,"_name":"cfg","contain":false}},
{"ALE":{"_id":4,"_name":"Lakt","contain":false}},
{"PRO":{"image":"","code":"123456","name":"jfbj"}},
{"USER":{"email":"[email protected]"}}
]';
$array = json_decode($string, true);
echo "<pre>";
//print_r($array);exit;
for ($i=0;$i<=(count($array)-1);$i++){
    //print_r($array[$i]);
    if (array_key_exists("ADI",$array[$i])) {
        $ArrVal = $array[$i]['ADI'];
        $id = $ArrVal['id'];
        $danger = $ArrVal['danger'];
        echo "$id,$danger ";
  }
}
?>
Sign up to request clarification or add additional context in comments.

Comments

1

check this out :

echo "<pre>";
print_r($array);

for ($i=0; $i < count($array); $i++) {
  if(isset($array[$i]["ADI"])){
    print_r($array[$i]["ADI"]);
  }

  if(isset($array[$i]["ALE"])){
    print_r($array[$i]["ALE"]);
  }
}
echo "</pre>";

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.