简体   繁体   中英

Fragmenting incoming data with PHP Json

The form of the incoming json data:

{
  "statusCode": 200,
  "message": "success",
  "result": [
    {
      "longitude": -87.06687,
      "start_location_latitude": 20.63589,
      "start_location_longitude": -87.06687,
      "end_location_latitude": 20.63589,
      "end_location_longitude": -87.06687,
      "highlights": [
        {
          "title": "Oh Yes...Mezcal Shots",
          "url": "https://phoenix-cdn.azureedge.net/phoenix-blob-public-exps/1396_Mezcal_Shot.jpg"
        },
        {
          "title": "Playa Del Carmen Beachfront",
          "url": "https://phoenix-cdn.azureedge.net/phoenix-blob-public-exps/1396_Playa_Del_Carmen-Beach_Punta_Esmeralda.jpg"
        },
        {
          "title": "Visit the Market",
          "url": "https://phoenix-cdn.azureedge.net/phoenix-blob-public-exps/1396_Playa_Del_Carmen.jpg"
        }
      ]
    }
  ]
}

This incoming data is combined into a single line.

https://phoenix-cdn.azureedge.net/phoenix-blob-public-exps/1396_Mezcal_Shot.jpghttps://phoenix-cdn.azureedge.net/phoenix-blob-public-exps/1396_Playa_Del_Carmen-Beach_Punta_Esmeralda.jpghttps://phoenix-cdn.azureedge.net/phoenix-blob-public-exps/1396_Playa_Del_Carmen.jpg

But what I want to do is to get the first 4 of these data, for example, by throwing them into separate variables and using them. However, I was never able to do that.

My code:

foreach($UnlockData as $highlights)
{
    foreach($highlights as $SingleImage)
    {
        if(strlen($SingleImage['url']) > 3) {
            echo $SingleImage['url'];
        }
    }
}

This will return the first 4 highlights from each entry in result . I am using the json object vs array because I find using it as objects makes for easier to read code.

<?php
$json = json_decode($incomingJSON);
foreach ($json->result as $result) {
  $ctr = 0 ;
  foreach($result->highlights as $highlight) {
    if (strlen($highlight->url) < 5) continue;

    echo "<P>" . $highlight->title. " - " . $highlight->url;

    $ctr ++;
    if ($ctr>3) break;
  }
}

If there is ever only one result then just get all the url from highlights (not clear why the strlen ):

$urls = array_column($array['result'][0]['highlights'], 'url');

foreach($urls as $url) {
    if(strlen($url) > 3) {
        echo $url;
    }
}

If there are multiple result then get all the highlights and then get all the url from that:

$urls = array_column(array_column($array['result'], 'highlights'), 'url']);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM