-2

How to write PHP for get data from this.

{"room":[{"single_room":1,"twin_room":3}]}{"total_amount":[{"amount":20899}]}{"travelernum":[{"total":1}]}

I tried like this

$BookingDetail["room"]["single_room"];

but got result like this

Illegal string offset 'room'

and

Illegal string offset 'single_room'

How to solve it.

Explorer
  • 1,491
  • 4
  • 26
  • 67
LPJ
  • 41
  • 1
  • 4

2 Answers2

0

Try this ... you need to decode the json, you get a PHP object and then you can access each element ..

<?php

$str = '{"room":[{"single_room":1,"twin_room":3}]}{"total_amount":[{"amount":20899}]}{"travelernum":[{"total":1}]}';

$json = json_decode($str);

echo "<pre>";
print_r($json);
echo "</pre>";

echo $json->room->single_room;

By the way, I think your json is invalid. You can check this out at http://jsonlint.com/

Chris
  • 4,672
  • 13
  • 52
  • 93
0

The string you are using looks like JSON but it doesn't check out as valid. See JSONLint.com... Editing it to make it valid (single line)...

{"room": [{"single_room": 1, "twin_room": 3}], "total_amount": [{"amount": 20899}], "travelernum": [{"total": 1 }]}

OR (Multi-Line)...

{
    "room": [{
        "single_room": 1,
        "twin_room": 3
    }],
    "total_amount": [{
        "amount": 20899
    }],
    "travelernum": [{
        "total": 1
    }]
}

If this is the format all your strings are in, you can manipulate them into valid JSON by first by using...

$original_string = '{"room":[{"single_room":1,"twin_room":3}]}{"total_amount":[{"amount":20899}]}{"travelernum":[{"total":1}]}';
$new_string = str_replace("}{", ",", $original_string);  // replace }{ with ,

Once your string is in valid JSON format, converting to a PHP array because rather simple, use something like this...

$BookingDetail = json_decode($new_string, true);  //true param gets assoc array

I tested all the code above and it works.See PHP json_decode() function reference for more detail on converting JSON strings to PHP Arrays.
http://php.net/manual/en/function.json-decode.php

Kris Tyte
  • 1
  • 3