PHP For Each value in object [duplicate] - php

This question already has answers here:
How to loop through PHP object with dynamic keys [duplicate]
(16 answers)
Closed 4 years ago.
im working on a project but I ran into a problem :(
I looked on the internet for like 2-3 hours and cannot find the way how to do it...
I retrieve this JSON from my database:
{
"articles": {
"1": {"discription":"Transport", "tax":"21", "price":"234"
},
"2": {"discription":"Opslag", "tax":"19", "price":"19"}
}
}
What I want to do next is retrieve the description,tax & Price from each object, how to do this with a for each loop on the most efficient way?
Thanks!

You can use following code snippet to get value of mentioned keys-
<?php
$str = '{
"articles": {
"1": {"discription":"Transport", "tax":"21", "price":"234"
},
"2": {"discription":"Opslag", "tax":"19", "price":"19"}
}
}';
//convert json to array
$jsonToArray = json_decode($str, true);
foreach ($jsonToArray['articles'] as $value) {
echo $value['discription'] . ' ' . $value['tax'] . ' ' . $value['price'] . PHP_EOL;
}
if you want to access those keys with object then you can proceed with following code snippet-
<?php
$str = '{
"articles": {
"1": {"discription":"Transport", "tax":"21", "price":"234"
},
"2": {"discription":"Opslag", "tax":"19", "price":"19"}
}
}';
//convert json to object
$jsonToObject = json_decode($str);
foreach ($jsonToObject->articles as $value) {
echo $value->discription . ' ' . $value->tax . ' ' . $value->price . PHP_EOL;
}
You are free to make changes in the echo statement that suits your requirement.
Checkout my all the technical post.

$array = json_decode($json_string);
for($i = 0; $i<sizeof($array); $i++) {
echo $array[$i]['description'];
echo $array[$i]['tax'];
echo $array[$i]['price'];
}

You are looking for the json_decode function before you do that, here's an example:
$jsonDecoded = json_decode($jsonInput);
foreach ($jsonDecoded->articles as $item) {
echo $item->discription . "<br>";
echo $item->tax . "<br>";
echo $item->price . "<br>";
}

Related

How do I get one json value value each?

in this my php code
echo $_POST[result];
in this my php result
{
"result_code":0,
"err_cd":"",
"result_msg":"",
"store_id":"M20C2685",
"status":"APPROVED",
"order_no":"600a2a044c9be",
"tr_no":725,
"tr_price":1000,
"pay_price":1000,
"approved_day":"20210122",
"approved_time":"102744",
"param1":"",
"param2":""
}
I want to print out each value one by one. What should I do?
json_decode Parsing JSON
<?php
$str = '{"result_code":0,
"err_cd":"",
"result_msg":"",
"store_id":"M20C2685",
"status":"APPROVED",
"order_no":"600a2a044c9be",
"tr_no":725,
"tr_price":1000,
"pay_price":1000,
"approved_day":"20210122",
"approved_time":"102744",
"param1":"",
"param2":""
}';
$arr = json_decode($str, true);
echo $arr['err_cd'] . PHP_EOL;
echo $arr['result_msg'] . PHP_EOL;
echo $arr['store_id'] . PHP_EOL;
echo $arr['status'] . PHP_EOL;
// ......
// Circulates each value in the array
foreach ($arr as $item) {
echo $item . PHP_EOL;
}

Loop through json (non-object ?)

I want to show a list of TV programs with title, genre, subgenre, description, start time and duration using a json file on server but I get the following errors:
E_NOTICE : type 8 -- Trying to get property of non-object -- at line 13
E_WARNING : type 2 -- Invalid argument supplied for foreach() -- at line 13
Here is a piece of a sample json:
{"channel":"6280",
"banned":true,
"plan":[
{"id":"-1",
"pid":"0",
"starttime":"00:00",
"dur":"65",
"title":"",
"normalizedtitle": "",
"desc":"",
"genre":"",
"subgenre":"",
"prima":false
},
{"id":"94622386",
"pid":"507461",
"starttime":"01:05",
"dur":"65",
"title":"Sex Researchers",
"normalizedtitle": "sex-researchers",
"desc":"Ep. 2 - Ciclo The Body of...",
"genre":"mondo e tendenze",
"subgenre":"societa",
"prima":false
},
Here is the php code that I use:
<?php
$channel = '6280';
$current_unix = time();
$json = json_decode(file_get_contents('http://guidatv.sky.it/app/guidatv/contenuti/data/grid/'.date('y_m_d').'/ch_'.$channel.'.js'));
//print_r($json);
echo '<ul>';
foreach ($json as $data) {
echo '<li>';
foreach ($data->plan as $prog) {
if ( $current_unix < $prog->starttime ) {
echo $prog->id . '<br>';
echo $prog->starttime . '<br>';
echo $prog->dur . '<br>';
echo $prog->desc . '<br>';
if ( isset($prog->genre)) {
echo $prog->genre . '<br>';
}
}
}
echo '</li>';
}
echo '</ul>';
?>
Could you help me to solve this problem? Thank you
You cannot loop on the object. Your JSON does not return the array of channel, but return only a channel object. Here is what you want:
$json = json_decode(file_get_contents('http://guidatv.sky.it/app/guidatv/contenuti/data/grid/'.date('y_m_d').'/ch_'.$channel.'.js'));
echo '<ul>';
foreach ($json->plan as $prog) {
echo "<li>" . $prog->title . '</li>';
}
echo '</ul>';

PHP get json data with json_decode

I'm new to PHP and try to echo out some data from json, but I got stucked in this.
It shows non of the data, but the data is there. The var_dump() shows it to me.
Probably I don't use the array correctly, but I can't find what's wrong. I've this code,
I request some data which I gathered with knockout.js
Knockout gives me a json (as show below)
$json = $_REQUEST[seats];
echo 'requested data raw '. "<br>".$json;
$data = json_decode($json, true);
echo "<br>".'var_dump '. "<br>";
var_dump($data);
foreach ($data as $optie ) {
echo "name = " . $optie->name . "<br>";
echo "optie = " . $optie->optieName . "<br>";
echo "prijs = " . $optie->prijs . "<br>";
}
This is my JSON:
[
{
"name": "Naam 1",
"optie": {
"optieName": "Make_up",
"prijs": 9.95
},
"PrijsFormated": "Euro: 9.95"
},
{
"name": "Naam 2",
"optie": {
"optieName": "Handverzorging",
"prijs": 12.95
},
"PrijsFormated": "Euro: 12.95"
}
]
You should use such loop:
foreach ($data as $optie ) {
echo "name = " . $optie['name'] . "<br>";
echo "optie = " . $optie['optie']['optieName'] . "<br>";
echo "prijs = " . $optie['optie']['prijs']. "<br>";
}
Because using json_decode() with second parameter as true you have created associative array - documentation.
If you would like to access data as object, you should use:
$data = json_decode($json);
instead of
$data = json_decode($json, true);
and then you should use the following loop:
foreach ($data as $optie ) {
echo "name = " . $optie->name . "<br>";
echo "optie = " . $optie->optie->optieName . "<br>";
echo "prijs = " . $optie->optie->prijs. "<br>";
}

PHP json, finding info and linking it with 4chan api

If I wanted to echo the link of a general thread on 4chan.
Here's what I was thinking of, however I have no idea on what to do
$jsonurl = "http://a.4cdn.org/vg/catalog.json";
$json = file_get_contents($jsonurl);
$json_output = json_decode($json);
foreach( $json_output as $no )
{
if(strpos(sub, 'DOTA')) { //Not sure how I would do this
//echo the "no" of it in the json
}
}
Had to look at the JSON data to see what you were looking for. Give this a try
$jsonurl = "http://a.4cdn.org/g/catalog.json";
$json = file_get_contents($jsonurl);
$json_output = json_decode($json);
foreach ($json_output as $page) {
foreach($page->threads as $thread) {
if (isset($thread->sub)) {
$sub = $thread->sub;
$no = $thread->no;
echo $sub . ', Thread Number: ' . $no . '<br />';
/*
if (strpos($sub, 'DOTA') !== false) {
echo 'Found DOTA!!! Thread Number is: ' . $thread->no;
}
*/
}
}
}
You should study the JSON data that you receive in order to know how to extract the data. This is one way of doing it:
foreach( $json_output as $page ) {
foreach ($page->threads as $t) {
echo 'http://boards.4chan.org/vg/res/' . $t->no . ', ';
}
}

Parsing pinterest JSON api with PHP

Hi im having problem parsing this pinterest JSON file, any ideas? thanks
$json = file_get_contents('http://pinterestapi.co.uk/jwmoz/boards');
$obj = json_decode($json);
foreach($obj->body as $item){
$example = $item[0]->name;
echo $example;
}
{
"body":[
{"name":"JMOZ",
"href":"http:\/\/pinterest.com\/jwmoz\/jmoz\/",
"num_of_pins":17,"cover_src":"http:\/\/media-cache-ec4.pinterest.com\/upload\/82190761920643849_2DcDfCUK_222.jpg",
"thumbs_src":
["http:\/\/media-cache-ec5.pinterest.com\/upload\/82190761920643841_dZfvCWmE_t.jpg",
"http:\/\/media-cache-ec4.pinterest.com\/upload\/82190761920194573_aPAbDtHD_t.jpg",
"http:\/\/media-cache-ec2.pinterest.com\/upload\/82190761920194563_dQcOIHvQ_t.jpg",
"http:\/\/media-cache0.pinterest.com\/upload\/82190761920194557_VSSI2uQB_t.jpg"
]
},
{"name":"JMOZ",
"href":"http:\/\/pinterest.com\/jwmoz\/jmoz\/",
"num_of_pins":17,"cover_src":"http:\/\/media-cache-ec4.pinterest.com\/upload\/82190761920643849_2DcDfCUK_222.jpg",
"thumbs_src":
["http:\/\/media-cache-ec5.pinterest.com\/upload\/82190761920643841_dZfvCWmE_t.jpg",
"http:\/\/media-cache-ec4.pinterest.com\/upload\/82190761920194573_aPAbDtHD_t.jpg",
"http:\/\/media-cache-ec2.pinterest.com\/upload\/82190761920194563_dQcOIHvQ_t.jpg",
"http:\/\/media-cache0.pinterest.com\/upload\/82190761920194557_VSSI2uQB_t.jpg"
]
},
{"name":"JMOZ",
"href":"http:\/\/pinterest.com\/jwmoz\/jmoz\/",
"num_of_pins":17,"cover_src":"http:\/\/media-cache-ec4.pinterest.com\/upload\/82190761920643849_2DcDfCUK_222.jpg",
"thumbs_src":
["http:\/\/media-cache-ec5.pinterest.com\/upload\/82190761920643841_dZfvCWmE_t.jpg",
"http:\/\/media-cache-ec4.pinterest.com\/upload\/82190761920194573_aPAbDtHD_t.jpg",
"http:\/\/media-cache-ec2.pinterest.com\/upload\/82190761920194563_dQcOIHvQ_t.jpg",
"http:\/\/media-cache0.pinterest.com\/upload\/82190761920194557_VSSI2uQB_t.jpg"
]
},
{"name":"test I\u00f1t\u00ebrn\u00e2ti\u00f4n\u00e0liz\u00e6ti\u00f8n",
"href":"http:\/\/pinterest.com\/jwmoz\/test-internationaliztin\/",
"num_of_pins":0,
"cover_src":false,
"thumbs_src":false
}],
"meta":{"count":11}
}
It seems the problem is in your usage of the [0] index on $item
$example = $item[0]->name;
This should just be
$example = $item->name;
To access the thumbnails, try
$obj = json_decode($json);
foreach($obj->body as $item){
echo '<li>' . $item->name . '<ul>';
if(!empty($item->thumbs_src))
{
foreach($item->thumbs_src as $thumbs_src){
echo '<li>' . $thumbs_src . '</li>';
}
}
echo '</ul></li>';
}

Categories