Asked  2 Years ago    Answers:  5   Viewed   86 times

I have an url passing parameters use json_encode each values like follow:

$json = array
(
    'countryId' => $_GET['CountryId'],
    'productId' => $_GET['ProductId'],
    'status'    => $_GET['ProductId'],
    'opId'      => $_GET['OpId']
);

echo json_encode($json);

It's returned a result as:

{  
  "countryId":"84",
  "productId":"1",
  "status":"0",
  "opId":"134"
}

Can I use json_decode to parse each values for further data processing?

Thanks.

 Answers

4

json_decode() will return an object or array if second value it's true:

$json = '{"countryId":"84","productId":"1","status":"0","opId":"134"}';
$json = json_decode($json, true);
echo $json['countryId'];
echo $json['productId'];
echo $json['status'];
echo $json['opId'];
Monday, October 24, 2022
3

What a HORRENDOUS debug session.. well there's good news.. I figured it out..

I started looking at it using AJAX and logging it with Firebug... and it turns out json_decode (or eval by the way) cannot handle ", which is what PHPUnit sends back (Come on Sebastian!), so to fix it:

$json = str_replace('"', '"', $json);

Now I thought they were the same.. maybe someone can enlighten me..

Friday, December 23, 2022
3

Try something like this:

$item_array = json_decode($json, true);
$insert_query = "INSERT INTO items (column1,column3) VALUES ";
$i = 0;
$array_count = count($item_array);

foreach($item_array as $item) {
 $end = ($i == $array_count) ? ';' : ',';
 $insert_query .= "('".$item['date']."','".$item['device_id']."')" . $end;
 $i ++;
}

mysql_query($insert_query);

The resulting query will look something like:

INSERT INTO items (column1,column3) VALUES ('asdf',123),('asdfe',1234);
Tuesday, November 22, 2022
 
coomie
 
3

Debugging suggestion:

Check the output of json_last_error(). It should give you an exact reason why it doesn't work. Available from PHP 5.3.0 only, though.

The reason:

JSONP is not identical with JSON. It contains extra data that breaks json_decode().

Solution:

Remove the extra brackets using substr($AVDecode, 1, strlen($AVDecode)-2)

Thursday, December 1, 2022
 
vladfr
 
4

Update I just reread your question and it looks like you intentionally concatenated the values. Since you are using json_encode it would be much better to send the values as an array, and simply access it in JavaScript.

echo json_encode(array($PostedDate, $Places, $Company, $Designation, $ProjectDetails, $DesiredCandidate, $HRName, $HRContact, $Email));

Then in JavaScript they would be accessed like this:

alert(data[1]); // Would alert the value of $Places
Saturday, September 24, 2022
 
Only authorized users can answer the search term. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :
 

Browse Other Code Languages