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.

Komal12
  • 3,340
  • 4
  • 16
  • 25
Muyi
  • 21
  • 1
  • 6
  • Try `json_decode()`: http://php.net/manual/en/function.json-decode.php – JustBaron Mar 27 '17 at 11:14
  • The array you're trying to loop through isn't in `$json['data']` - it's in `$json['data']['onward']` – Tom Mar 27 '17 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? – Aman Rawat Mar 27 '17 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! – Muyi Mar 27 '17 at 11:17

2 Answers2

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?

Community
  • 1
  • 1
Aman Rawat
  • 2,625
  • 1
  • 25
  • 40
  • Same for me except for a loop in the end and i get expected result. closed case if you ask me – Louis Loudog Trottier Mar 27 '17 at 11:34
  • @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? – Muyi Mar 27 '17 at 11:47
  • 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 Mar 27 '17 at 12:07
  • @Aman Rawat : Thank! Works perfectly. Just if you could help me with the sort simply? Sort by lowest price first then so on. – Muyi Mar 27 '17 at 12:13
  • @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? – Muyi Mar 27 '17 at 12:29
  • @AmanRawat 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? – Muyi Mar 28 '17 at 16:04
  • Thanks @AmanRawat. Sorry for being so cheesy, just getting my hands on this. Thank for all the help. Highly obliged. Any way to hide objects with specific id? Like i don't want objects with EH10 to be displayed. – Muyi Mar 28 '17 at 18:22
  • This works fine. But the problem is that my json has another object by cid name (not shown in above sample code), how can i unset on the basis of cid? Like don't show items with cid = 101. Thanks again. Answer accepted! – Muyi Mar 29 '17 at 06:42
  • @AmanRawat This works fine. But the problem is that my json has another object by cid name (not shown in above sample code), how can i unset on the basis of cid? Like don't show items with cid = 101. Thanks again. Answer accepted! – Muyi Mar 29 '17 at 07:39
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

Louis Loudog Trottier
  • 1,367
  • 13
  • 26
  • $json=json_decode ($response, true); $output=""; foreach($json['data']['onward'] as $data) { $output.="ID : ".$data['origin']; } echo $output; Output is a blank screen! – Muyi Mar 27 '17 at 11:20
  • 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 – Louis Loudog Trottier Mar 27 '17 at 11:29