Jump to content

Read data from multi-array?


Go to solution Solved by FIll1992,

Recommended Posts

I have the following data, and would like to store the values "price", "status" and "name" in variables. However, I don't understand how to access the individual values. I have already tried it with loops (forearch), but without much success :(

{
  "newOffers": null,
  "usedOffers": [
    {
      "id": 386018798099,
      "price": 49.23,
      "deliveryRate": 0,
      "deliveryTime": "Mi. 26. - Do. 27. Juli",
      "deliveryTimeRange": {
        "min": "2023-07-26T00:00:01+02:00",
        "max": "2023-07-27T23:59:59+02:00"
      },
      "fulfillmentType": "seller",
      "isHauler": false,
      "condition": {
        "status": "Gebraucht - Akzeptabel",
        "text": "Nintendo Switch Spiel Mario Kart 8 Deluxe nur Modul ohne OVP - nur Modul, gebraucht, getestet, funktionsfähig. Altersbedingte Gebrauchsspuren möglich. Meist Erstauflage. Download Codes i.d.R. bereits eingelöst. Sprache i.d.R. dt/engl. PAL Version. Mu"
      },
      "seller": {
        "id": 654591,
        "name": "better-used",
        "isDirectSeller": false,
        "returnPeriod": "P1M",
        "freeReturnOptions": "advanced",
        "shopURL": "/shops/better-used"
      },
      "priceThreshold": {
        "isAbove": true,
        "value": 40
      }
    },
    {
      "id": 386015598582,
      "price": 49.49,
      "deliveryRate": 0,
      "deliveryTime": "Mi. 26. - Do. 27. Juli",
      "deliveryTimeRange": {
        "min": "2023-07-26T00:00:01+02:00",
        "max": "2023-07-27T23:59:59+02:00"
      },
      "fulfillmentType": "seller",
      "isHauler": false,
      "condition": {
        "status": "Gebraucht - Sehr gut",
        "text": "Sehr gut in OVP und Anleitung"
      },
      "seller": {
        "id": 44296521,
        "name": "DorAdos",
        "isDirectSeller": false,
        "returnPeriod": "P14D",
        "freeReturnOptions": "default",
        "shopURL": "/shops/Dorados"
      },
      "priceThreshold": {
        "isAbove": true,
        "value": 40
      }
    },
    {
      "id": 386289767027,
      "price": 55.56,
      "deliveryRate": 0,
      "deliveryTime": "Mi. 26. - Do. 27. Juli",
      "deliveryTimeRange": {
        "min": "2023-07-26T00:00:01+02:00",
        "max": "2023-07-27T23:59:59+02:00"
      },
      "fulfillmentType": "seller",
      "isHauler": false,
      "condition": {
        "status": "Gebraucht - Wie neu",
        "text": "Nintendo Switch Spiel Mario Kart 8 Deluxe in OVP komplett in OVP -  - Artikel lagernd, vom Fachhändler, Versand aus Deutschland. Weitere Spiele, Konsolen und Zubehör findest Du bei uns im Real Shop. Viel Spaß beim Zocken wünscht dir das better-used-T"
      },
      "seller": {
        "id": 654591,
        "name": "better-used",
        "isDirectSeller": false,
        "returnPeriod": "P1M",
        "freeReturnOptions": "advanced",
        "shopURL": "/shops/better-used"
      },
      "priceThreshold": {
        "isAbove": true,
        "value": 40
      }
    }
  ],
  "fbk": {
    "offersToDeliveryGroups": null
  }
}

Can anyone help me here? (Source: https://api.cloud.kaufland.de/pdp-frontend/v1/316951680/offers?offset=0&limit=10&condition=used)

Edited by FIll1992
Link to comment
https://forums.phpfreaks.com/topic/317117-read-data-from-multi-array/
Share on other sites

That's JSON. Can I assume you've already json_decode-d it?

Here's how to read that output:

{

The value you get back from json_decode represents an object. If you decoded it as an object (the default behavior) then you will have PHP objects to work with; if you told it to decode to associative arrays then the JSON objects will be PHP arrays.

To get to the price, status, and name, first you have to get to

  "usedOffers": [

the usedOffers list. That means you need ->usedOffers or ["usedOffers"] on whatever variable you're using for the decoded JSON. The [ means this value will be an array.

Since there are multiple items in this array, you need a foreach to get the next thing to work with.

Each of those

    {

will be an object (or associative array). The price is immediately available from there.

For the condition status, you continue from there by getting

      "condition": {

the condition, which is also an object (or associative array), and from that you can get the status.
Similarly, the name is under the "seller" object.

 

If you have trouble, post your code and describe both what you expected to happen as well as what actually happened.

A simple way in my opinion would to do something like the following.

fetch('https://example.com/data-endpoint') // replace with your actual URL
  .then(response => {
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    return response.json(); // this returns a promise
  })
  .then(data => {
    console.log(data); // this will log the whole data to the console

    // you can access any data point like this:
    console.log(data.newOffers); // logs: null
    console.log(data.usedOffers[0].price); // logs: 49.23

    // if you want to loop through all the usedOffers you can do something like this:
    data.usedOffers.forEach(offer => {
      console.log(`Offer ID: ${offer.id}`);
      console.log(`Price: ${offer.price}`);
      console.log(`Delivery Rate: ${offer.deliveryRate}`);
      // ... and so on for other properties
    });
  })
  .catch(e => {
    console.log('There was a problem with the fetch operation: ' + e.message);
  });

I'm half asleep that from the JavaScript side, but I find JavaScript more flexible than PHP and easier.

Edited by Strider64

Thanks for the great help so far. I would like to use PHP as the application runs in the background on the server.  So far I have the following code:

 

$timestamp=time();

$uri = "https://api.cloud.kaufland.de/pdp-frontend/v1/316951680/offers?offset=0&limit=10&condition=used";

// Define all the mandatory headers
$headers = [
	'Accept: application/json',
	'Hm-Timestamp: ' . $timestamp,
];

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $uri);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);


$ch = json_decode(curl_exec($ch), true);

foreach ($ch as $key => $value) {
echo $ch['usedOffers'][0]['id'];
echo '<br/>';
}

Issue, however, is:

386018798099
386018798099
386018798099

However, I deliberately accessed only the value "0" in the code. How do I now achieve that all values from "0", "1", "2" etc. are displayed? I do not always know the number of inner arrays?

Edited by FIll1992
  • Solution

Thanks all for the Help! I have found the Solution:

 

<?php

$timestamp=time();

$uri = "https://api.cloud.kaufland.de/pdp-frontend/v1/316951680/offers?offset=0&limit=10&condition=used";

// Define all the mandatory headers
$headers = [
	'Accept: application/json',
	'Hm-Timestamp: ' . $timestamp,
];

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $uri);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);


$ch = json_decode(curl_exec($ch), true);

foreach ($ch["usedOffers"] as $area) {
  $arrayname=$area["seller"]["name"];
  $arrayprice=$area["price"];
  echo '<br/>';
  echo ''.$arrayname.' hat den Artikel für '.$arrayprice.' gelistet.';
}

?>

 

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.