1

I am trying to echo the following JSON response to html using php.

This is the JSON response :

{
  "data": {
    "onward": [
      {
        "origin": "LHR",
        "id": "SB15",
        "rating": 0,
        "destination": "FKK",
        "PricingSolution": {
          "TotalPrice": "USD445"
        },
        "Class": "Eco"
      },
      {
        "origin": "LHR",
        "id": "EH10",
        "rating": 0,
        "destination": "FKK",
        "PricingSolution": {
          "TotalPrice": "USD223"
        },
        "Class": "Eco"
      }
    ]
  }
}

This is how it should appear in html :

<body>
<ul class="myclass">
<li>ID: EH10, Price: 223, Class: Eco</li>
<li>ID: SB15, Price: 445, Class: Eco</li>
</ul>
</body>

I want it somehow to be sorted by Total price in Ascending order.

Tried

foreach($json['data'] as $data). 

Doesn't seem to be working! Please help.

4
  • Try json_decode(): php.net/manual/en/function.json-decode.php Commented Mar 27, 2017 at 11:14
  • The array you're trying to loop through isn't in $json['data'] - it's in $json['data']['onward'] Commented Mar 27, 2017 at 11:14
  • Doesn't seem to be working! Whats not working, how is your output looks like? Are you getting any error or warning? Commented Mar 27, 2017 at 11:14
  • $json=json_decode ($response, true); $output=""; foreach($json['data']['onward'] as $data) { $output.="ID : ".$data['origin']; } echo $output; Output is a blank screen! Commented Mar 27, 2017 at 11:17

2 Answers 2

1

I have executed the code and it's working great.

Check this

<?php

$jsonString = '{
"data": {
"onward": [
{
"origin": "LHR",
"id": "SB15",
"rating": 0,
"destination": "FKK",
"PricingSolution":{
"TotalPrice": "USD442"
},
"Class": "Eco"
},
{
"origin": "LHR",
"id": "SB15",
"rating": 0,
"destination": "FKK",
"PricingSolution":{
"TotalPrice": "USD445"
},
"Class": "Eco"
},

{
"origin": "LHR",
"id": "EH10",
"rating": 0,
"destination": "FKK",
"PricingSolution":{
"TotalPrice": "USD223"
},
"Class": "Eco"
}
]
}
}';

$json = json_decode($jsonString, true);

$items = $json['data']['onward'];

usort($items, function ($a, $b) {
    return (extractPrice($a['PricingSolution']['TotalPrice']) - extractPrice($b['PricingSolution']['TotalPrice']));
});

function extractPrice($price)
{
    return str_replace('USD', '', $price);
}

$finalItems = []; // Duplicate ids handling
foreach ($items as $item) {
    if (empty($finalItems[$item['id']]) || extractPrice($finalItems[$item['id']]['PricingSolution']['TotalPrice']) > extractPrice($item['PricingSolution']['TotalPrice'])) {
        $finalItems[$item['id']] = $item;
    }
}

?>
<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
<ul class="myclass">
    <?php foreach ($finalItems as $item) { ?>
        <li>ID: <?= $item['id']; ?>, Price: <?= $item['PricingSolution']['TotalPrice']; ?>,
            Class: <?= $item['Class']; ?></li>
    <?php } ?>
</ul>
</body>
</html>

If you want to do sorting then check this link

How can I sort arrays and data in PHP?

Sign up to request clarification or add additional context in comments.

9 Comments

Same for me except for a loop in the end and i get expected result. closed case if you ask me
@AmanRawat Works great! Thanks. Just if you could help me with the sorting stuff with some simple code? I'm just a beginner. And is there anyway we can subtract some number from TotalPrice? Like TotalPrice - 50?
In the TotalPrice 'USD' is at the start so remove that USD and then subtract. Like this <?= str_replace('USD', '',$item['PricingSolution']['TotalPrice']) - 50; ?>
@Aman Rawat : Thank! Works perfectly. Just if you could help me with the sort simply? Sort by lowest price first then so on.
@Aman Rawat : Thankyou so very much for all the help. Everything works like a charm. You'the champ! Just one last question, In the JSON response, at times there are objects with similar "id", like two objects with id EH10 for example. In that case how do we prevent duplicate echo and have echo of EH10 with lowest price?
|
0

use json_decode to transform your json into a php array (with the 2nd parameter as true so it is cast as an associative array)

PHP manual for json_decode

Then you can loop the array.

$array=json_decode($json,true);
foreach($array as $key=>$value){
  //do your magic
}

I've ran this fiddle

<?php
$json=json_decode ('{
"data": {
"onward": [
{
"origin": "LHR",
"id": "SB15",
"rating": 0,
"destination": "FKK",
"PricingSolution":{
"TotalPrice": "USD445"
},
"Class": "Eco"
},

{
"origin": "LHR",
"id": "EH10",
"rating": 0,
"destination": "FKK",
"PricingSolution":{
"TotalPrice": "USD223"
},
"Class": "Eco"
}
]
}
}',true);

echo "<pre>";
foreach($json['data']['onward'] as $k=>$v){
echo "ID :" .$v['id'];
}
echo "</pre>";
?>

and got expected output :

ID :SB15ID :EH10

2 Comments

$json=json_decode ($response, true); $output=""; foreach($json['data']['onward'] as $data) { $output.="ID : ".$data['origin']; } echo $output; Output is a blank screen!
well check your error log and see what happend, i mean this is basic stuff. you will figure it out. I ran a PHP fiddle and i get the expected ID

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.