PHP Json values with a specified label - php

I am using json_decode and echoing the values using a nested foreach loop.
Here's a truncated json that I am working on:
[{"product_name":"Product 1","product_quantity":"1","product_price":"2.99"},....
and the loop
foreach($list_array as $p){
foreach($p as $key=>$value) {
$result_html .= $key.": ".$value."<br />";
}
}
This was I am able to echo all key/value pairs.
I have tried using this to echo individual items something like:
foreach($list_array as $p){
foreach($p as $key=>$value) {
echo "Product: ".$p[$key]['product_name'];
echo "Quantity: ".$p[$key]['product_quantity'];
}
}
However I am unable to because it doesn't echo anything.
I would like to be able to show something like:
Product Name: Apple
Quantity: 7
Currently it is showing:
product_name: Apple
product_quantity: 7
How can I remove the key and replace it with a predefined label.

It can be done with:
foreach ($list_array as $p){
$result_html .= 'Product: ' . $p->product_name
. 'Quantity: ' . $p->product_quantity . '<br />';
}

If you are decoding your json into an object you can do it like that.
$list_array = json_decode('[{"product_name":"Product 1","product_quantity":"1","product_price":"2.99"}]');
$result_html = '';
foreach($list_array as $p){
$result_html .= '<div>Product: '.$p->product_name.'</div>';
$result_html .= '<div>Quantity: '.$p->product_quantity.'</div>';
}
echo $result_html;

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;
}

How to get value from next iteration of foreach loop

I'm trying to print out entries from a SQL database. Some of the entries are images, and I want to parse those and put them in appropriate HTML markup.
Database Example
id | datatype | typetext
78 | paragraph | "hello"
79 | image | "image.jpg"
80 | paragraph | "goodbye"
The column datatype signifies what type of data is being stored in a given row, and I want to catch when the value of datatype is "image" - then jump to the following typetext column and prepare the appropriate markup for this image.
For instance, some psuedo-code of what I'm trying to do:
if(column is datatype){
if(datatype == 'image'){
echo '<p>' . data inside accompanying typetext column . '</p>';
}
}
Here's my current code:
//the array of the blog entry
foreach($entry as $key => $entryUnit){
//the array of the entry unit
foreach($entryUnit as $column => $cell){
if($column == 'datatype'){
if($key == 'image'){
echo '<br/>';
echo '<p style="color: pink;">' $cell . $entryUnit[$column + 1] . '</p>';
echo '<br/>';
}
}
else if($column == 'typetext'){
echo '<br/>';
echo $cell;
echo '<br/>';
}
}
}
In the first if statement, I try jumping to the next column with echo '<p style="color: pink;">' $cell . $entryUnit[$column + 1] . '</p>';, but this doesn't work.
I've also tried utilizing the next() function, like:
echo '<p>' . next($cell) . '</p>';`
..but this also doesn't work as I thought it would.
You don't need that nested foreach loops, you can everything in just one simple foreach loop.
foreach($entry as $entryUnit){
if($entryUnit['datatype'] == "image"){
echo '<br/>';
echo '<p style="color: pink;">' . $entryUnit['typetext'] . '</p>';
echo '<br/>';
}elseif($entryUnit['datatype'] == "paragraph"){
echo '<br/>';
echo $entryUnit['typetext'];
echo '<br/>';
}
}
Somethink like this should work:
//the array of the blog entry
foreach($entry as $key => $entryUnit){
$i=0;
//the array of the entry unit
foreach($entryUnit as $column => $cell){
if($column == 'datatype'){
if($key == 'image'){
$i++;
echo '<br/>';
echo '<p style="color: pink;">' $cell . $entryUnit[$i] . '</p>';
echo '<br/>';
}
}
else if($column == 'typetext'){
echo '<br/>';
echo $cell;
echo '<br/>';
}
}
}

How to print jSON values with loop

I am using the following code to print the output of the jSON response but when I try to print
echo $obj->HotelListResponse->customerSessionId; // This is working.
echo $obj->HotelListResponse->HotelList->HotelSummary->name; // This is not working.
When the response contains only one node then its printing perfectly but when there are multiple nodes with same name then its not printing. I tried using foreach just like the below. I also tried using while loop but still I am unable to print the list of hotel names.
My jSON decoded output is like http://pastebin.com/Fr21DkEk
Total code:
$url = "https://api.eancdn.com/ean-services/rs/hotel/v3/list?cid=55505&minorRev=99&apiKey=cbrzfta369qwyrm9t5b8y8kf&locale=en_AU&currencyCode=AUD&xml=<HotelListRequest><city>Brisbane</city><stateProvinceCode>QLD</stateProvinceCode><countryCode>AU</countryCode><arrivalDate>10/16/2014</arrivalDate><departureDate>10/18/2014</departureDate><RoomGroup><Room><numberOfAdults>2</numberOfAdults></Room></RoomGroup><numberOfResults>25</numberOfResults></HotelListRequest>";
$json = file_get_contents($url);
$obj = json_decode($json);
foreach($obj as $val) {
echo $val->HotelListResponse->HotelList->HotelSummary->name;
}
Try this
foreach($obj->HotelListResponse->HotelList->HotelSummary as $val) {
echo $val->name . '<br/>';
}
HotelSummary is an array:
echo $val->HotelListResponse->HotelList->HotelSummary[0]->name;
If you want all of the hotel summaries:
foreach($obj as $val) {
foreach($val->HotelListResponse->HotelList->HotelSummary as $sum) {
echo $sum->name;
}
}
Yes you can directly access them inside the foreach. Like this:
foreach($obj->HotelListResponse->HotelList->HotelSummary as $val) {
// ^^
// since you're interested on just names, you can point it directly on that object, then each of that batch is in `$val`
echo $val->name . '<br/>';
}
// or start from the parent
foreach($obj as $values) {
$customerSessionId = $values->customerSessionId;
echo $customerSessionId . '<hr/>';
$hotelList = $values->HotelList;
foreach($hotelList->HotelSummary as $hotelsummary) {
echo $hotelsummary->name . '<br/>';
}
}

Echo selective data (rows) from multidimensional array in PHP

I have an array coming from a .csv file. These are coming from a real estate program. In the second column I have the words For Sale and in the third column the words For Rent that are indicated only on the rows that are concerned. Otherwise the cell is empty. I want to display a list rows only For Sale for example. Of course then if the user clicks on a link in one of the rows, the appropriate page will be displayed.
I can't seem to target the text in the column, and I can't permit that the words For Sale be used throughout the entire array because they could appear in another column (description for example).
I have tried this, but to no avail.
/* The array is $arrCSV */
foreach($arrCSV as $book) {
if($book[1] === For Sale) {
echo '<div>';
}
echo '<div>';
echo $book[0]. '<br>';
echo $book[1]. '<br>';
echo $book[2]. '<br>';
echo $book[3]. '<br>';
echo $book[6]. '<br><br><br>';
echo '</div>';
}
I also tried this:
foreach($arrCSV as $key => $book) {
if($book['1'] == 'For Sale') {
echo '<div>';
}
echo '<div>';
echo $book[0]. '<br>';
echo $book[1]. '<br>';
echo $book[2]. '<br>';
echo $book[3]. '<br>';
echo $book[6]. '<br><br><br>';
echo '</div>';
}
Do you mean:
foreach($arrCSV as $key => $book) {
if($book['1'] == 'For Sale') {
echo '<div></div>';
}else{
echo '<div>';
echo $book[0]. '<br>';
echo $book[1]. '<br>';
echo $book[2]. '<br>';
echo $book[3]. '<br>';
echo $book[6]. '<br><br><br>';
echo '</div>';
}
}
I found a solution here:
PHP: Taking Array (CSV) And Intelligently Returning Information
$searchCity = 'For Sale'; //or whatever you are looking for
$file = file_get_contents('annonces.csv');
$results = array();
$lines = explode("\n",$file);
//use any line delim as the 1st param,
//im deciding on \n but idk how your file is encoded
foreach($lines as $line){
//split the line
$col = explode(";",$line);
//and you know city is the 3rd element
if(trim($col[1]) == $searchCity){
$results[] = $col;
}
}
And then:
foreach($results as $Rockband)
{
echo "<tr>";
foreach($Rockband as $item)
{
echo "<td>$item</td>";
}
echo "</tr>";
}
As you can see I'm learning. It turns out that by formulating a question, a series of similar posts are displayed, which is much quicker and easier than using google. Thanks.

Is there something wrong with this foreach code?

foreach ($data['tests'] as $testname => $tests) {
echo "<h1>Extraction $testname Tests</h1>\n";
$function = $testfunctions[$testname];
echo "<ul>";
foreach ($tests as $test) {
echo "<li>" . $test['description'] . ' ... ';
$extracted = $extractor->$function($test['text']);
if ($test['expected'] == $extracted) {
echo " <span style='color: green'>passed.</span></li>";
} else {
echo " <span style='color: red'>failed.</span>";
echo "<pre>Original: " . htmlspecialchars($test['text']) . "\nExpected: " . print_r($test['expected'], true) . "\nActual : " . print_r($extracted, true) . "</pre>";
}
echo "</li>";
}
echo "</ul>";}
I keep getting the error:
Warning: Invalid argument supplied for
foreach() in
C:\xampp\htdocs\test\runtests.php on
line 49
p.s. the beginning of the code is line 49, so the probelm starts with the foreach statment.
Whenever i see that, it tends to mean that the thing i'm trying to iterate through isn't an array.
Check $data['tests'] (and each inner $tests) to make sure it's not null/unset/empty, and that it's something iterable like an array. Also keep in mind that older versions of PHP (before 5.0?) don't do iterable objects very well.
One of the elements in $data["tests"] is probably not an array.
Add this before the foreach:
if (is_array($tests))
foreach ($tests as $test) {...

Categories