How to loop through all Amazon API array Book results in PHP - php

I am trying to consume an Amazon Product API and I choose to search for books alone base on the user search query. However after converting the response to an array, I am having problem looping through all the result without having to specify an index.
Below is my Code:
<div class="album py-5 bg-light">
<div class="container">
<div class="row">
<?php
foreach($formattedResponse as $response) {
?>
<div class="col-md-8">
<div class="card mb-4 box-shadow">
<img class="card-img-top" data-src="" alt="Card image cap">
<div class="card-body">
<p class="card-text"></p>
<div class="d-flex justify-content-between align-items-center">
<div class="btn-group">
<button type="button" class="btn btn-sm btn-outline-secondary">Arthur: <?php echo $response['Item'][0]['ItemAttributes']['Author']; ?></button>
<button type="button" class="btn btn-sm btn-outline-secondary">Title: <?php echo $response['Item'][0]['ItemAttributes']['Title']; ?></button>
</div>
<small class="text-muted">Price: <?php echo $response['Item'][0]['ItemAttributes']['ListPrice']['FormattedPrice']; ?> </small>
</div>
</div>
</div>
</div>
<?php
}
?>
</div>
</div>
</div>
Displaying the results works perfectly, the only drawback is, it fetches only the first index of the returned book response out of the thousands present because I used $response['Item'][0] if I take away the [0] from I get an error.. Below is the result
Arthur: Harry Boone Porter
Title: The Day of Light
Price: $8.00
My Question:
The array contains [0],[1],[2] to [1000] How can I fetch all the book results in the above format instead of the first index which I am using.
Here is my Array Code Snippet: https://pasteio.com/xlsoTVWJLGBO

Seems like formatted response is the named array and does not have to be iterated with foreach loop, if I'm not mistaken, you just need to:
Pass to the view not the $formattedResponse but $formattedResponse['item'] and not to iterate through it. Lets call it $items.
$items = $formattedResponse['item'];
// pass $items to the view.
In ['item'] element you have an indexed array with numbers. So iterate through it
<?php foreach ($items as $item): ?>
... html here
<?= htmlspecialchars($item['ItemAttributes']['ListPrice']['FormattedPrice']) ?>
<?php endforeach; ?>
Do not forget to escape output for your views. Use Twig, Blade or something like Html::encode($var) from Yii. How to escape output in PHP
To make debugging of multidimensional large arrays easier install larapack/dd from composer, and add
dd($largeArray)
in any place of your code. It's like var_dump, but a lot easier to look for human being ;)

Related

PHP and JSON entering inside a Div

So, I have a JSON array, which parses just fine in the layout view, but the elements from json stack vertically and I need them to be horizontally aligned.
Here is the example code
<div class="swiper-container mySwiper2 swiper-container-h">
<div class="swiper-wrapper">
<div class="swiper-slide swiper-padding">
<?php include_once("team_hq.php"); ?>
</div>
<div class="swiper-slide swiper-padding bkg bkg3">
<h2>Partners</h2>
<?php
showStuff($stuff, "Partners"); ?>
</div>
<div class="swiper-slide swiper-padding bkg bkg12">
<h2>Production</h2>
<?php showStuff($stuff, "Production"); ?>
</div>
<div class="swiper-slide swiper-padding bkg bkg13">
<h2>Sales</h2>
<?php showStuff($stuff, "Sales"); ?>
</div>
<div class="swiper-slide swiper-padding bkg bkg14">
<h2>Support</h2>
<?php showStuff($stuff, "Support"); ?>
</div>
</div>
<div class="swiper-button-next"></div>
<div class="swiper-button-prev"></div>
<div class="swiper-pagination"></div>
</div>
The question I'm asking is how can I make the content which is pulled from the $stuff variable present horizontally instead of vertically as is now.
To position HTML elements horizontal either use:
Flexbox or CSS-Grid or Floating
But assuming your function showStuff just prints a JSON string, you'd have to work with your $stuff variable. E.g. loop over the it's content – with PHP I suppose – and build the HTML-Tags according your needs.

How to change link for each item in foreach loop in PHP?

Totally no experience with PHP and I need to change some little thing by my self, the developer has made a generic html component with a generic link ("href=#"). This should be different for each item in foreach loop. Pretty simple but totally difficult who doesnt know the syntax.
Anyone a quick fix?
<?php foreach ($pricing['price_box'] as $box) :?>
<div class="col-lg-6 mb-4 mb-lg-0">
<div class="p-4 pl-5 pr-5 pb-5">
<h3 class="text-center pt-4 pb-5"><?php echo $box['title'] ?></h3>
<div class="d-md-flex justify-content-md-between mb-5">
<?php echo $box['detail'] ?>
<div class="price-unit align-self-center">
<?php
$priceArray = explode('.', $box['price']);
echo $box['price'] ? $priceArray[0] . ",<span>$priceArray[1]</span>" : ''
?>
<div><?php echo $box['duration'] ?></div>
</div>
</div>
<div class="text-center">
Registreren
</div>
</div>
</div>
<?php endforeach; ?>
Since the anchor tag is inside the foreach loop, you can use the $box variable in the anchor tag.
Also, you can use the php variable inside the html by echo it.
For example, if your link is something like some_php_script.php?id=XXX and you want to replace the xxx with a unique id, you can use it like:
Registreren
assumes that the $box array contains an index called id.
Read more about php echo function.
Read more about php arrays here.
Assuming you need to change the link here :
<div class="text-center">
Registreren
</div>
As it is already in the loop, and you have $box array, you need to find out on which index the link href and text(the one you need to display instead of Registreren ) is available. Suppose you have the link at index link and text is at text, then your code will be like
<div class="text-center">
<?php echo $box['text'];?>
</div>
You can check the array structure using print_r()
Reference
Arrays
foreach

How to Pass the Data from one page to another page through URL Parameter

IN the PHP File the Brand value is Showing but when I trying to get it through another page it return NULL.
Page1
PHP
<div class="col-md-6">
<div class="row vertical-divider-page3">
<div class="col-md-4">
<div class="page3-img">
<img src="<?php echo $value["Image"]; ?>" class="img-responsive" id="custompage">
</div>
</div>
<div class="col-md-8">
<div class="page4">
<h3 id="custompage"><?php echo $value["Brand"]; ?><span><br><?php echo $value["Reference"]; ?></span></h3>
</div>
</div>
</div>
</div>
Product Page
It looks like you were trying to pass $value into your url which won't work for two reasons.
You didn't echo this value in PHP so you're literally just passing the string $value. Looks like you're trying to pass the 'Brand' along so you'll need to make sure your url query parameter is 'Brand=$value["Brand"]' and not just $value.
$value is an array and you cannot pass an array into the url like you are trying to do.
<h3 id="custompage"><?php echo $value["Brand"]; ?><span><br><?php echo $value["Reference"]; ?></span></h3>

Php to auto populate grids

I have the following html code:
<div class="media row-fluid">
<div class="span3">
<div class="widget">
<div class="well">
<div class="view">
<img src="img/demo/media/1.png" alt="" />
</div>
<div class="item-info">
Title 1
<p>Info.</p>
<p class="item-buttons">
<i class="icon-pencil"></i>
<i class="icon-trash"></i>
</p>
</div>
</div>
</div>
<div class="widget">
<div class="well">
<div class="view">
<img src="img/demo/media/2.png" alt="" />
</div>
<div class="item-info">
This is another title
<p>Some info and details go here.</p>
<p class="item-buttons">
<i class="icon-pencil"></i>
<i class="icon-trash"></i>
</p>
</div>
</div>
</div>
</div>
Which basically alternates between a span class with the widget class, and then the widget class without the span3 class.
What I wanted to know was if there was a way to have php "echo" or populate the details for and details under the "item-info" class. Would I need to use a foreach statement to get this done? I would be storing the information in a mysql database, and while I can get it to fill in the info one by one (repeatedly entering the and echoing out each image and item title) it's not practical when the content needed to be displayed is over 15 different items. I'm not well versed in foreach statements so I could definitely use some help on it.
If someone could help me perhaps structure a php script so that it can automatically output the html based on the number individual items in the database, that'd be greatly appreciated!
I'm wondering if the html + php (not including the foreach) would look like this:
<div class="span3">
<div class="widget">
<div class="well">
<div class="view">
<img src="img/<? $file ?>" alt="" />
</div>
<div class="item-info">
<?$title?>
<p>Info.</p>
<p class="item-buttons">
<i class="icon-pencil"></i>
<i class="icon-trash"></i>
</p>
</div>
</div>
</div>
EDIT:
I wanted to add some more information. The items populated would be based on a type of subscription - which will be managed by a group id.
I was initially going to use <? (if $_SESSION['group_id']==1)>
echo <div class="item-info">
$title
<p>$info</p>
</div>
so that only the subscribed items would populate. But, I would need it to iterate through all the items for group1 table and list it. Currently I know that I can do
<? (if $_SESSION['group_id']==1)
while ($row=mysql_fetch_assoc($sqlItem))
{
$itemInfo = $row['info'];
$image = $row['image'];
$title = $row['title'];
$url = $row['url'];
};
>
$sqlItem for now can only be assigned one thing (manually - as in: $sqlItem = '123'), unless I iterate through which is what I'm trying to figure out.
Just read that 'mysql_fetch_assoc' is being depreciated with 5.5, here is the new way and looks better, easier I think.. Hope this helps, was updated today.
I hope this helps http://php.net/manual/en/mysqli-stmt.fetch.php
replace the printf with echo '//then your html stuff
This will iterate through the rows in your database until their are no more matching records.
shouldn't a while be enough? It depends on the structure of your database and website (we didn't need so much HTML I think. Some more PHP maybe). Hope this helps.

issue with While statement

So I am trying to pull HEADLINES.. that I have saved in a DB, they all have unique IDs.. I need a way to be able to call them but type or ID for instance.
$stmt = $con->prepare("SELECT * FROM news WHERE type = 'sports'");
$stmt->execute();
while($rfr=$stmt->fetch(PDO::FETCH_ASSOC))
{
?>
<div class="row">
<div class="col-lg-4">
<img src="<?php echo $rfr['folder'] . $rfr1['file'];?>.jpg" >
<h2><?php echo $rfr['headline'];?></h2>
<p>V.A. conducts study to determine effectiveness</p>
<p><a class="btn btn-primary" href="#" role="button">Read More »</a></p>
</div>
<div class="col-lg-4">
<img src="imgs/news/n4.jpg">
<h2><?php echo $rfr['headline'];?></h2>
<p>The Rev. Daniel Berrigan, a Roman Catholic priest and peace activist who was imprisoned for burning draft files in a protest against the Vietnam War, died Saturday. He was 94.</p>
<p><a class="btn btn-primary" href="#" role="button">Read More »</a></p>
</div>
<div class="col-lg-4">
<img src="imgs/news/n1.jpg">
<h2><?php echo $rfr['headline'];?></h2>
<p>President Barack Obama is getting one more chance to poke fun at fellow politicians, the press and himself at the annual White House Correspondents' Dinner.</p>
<p><a class="btn btn-primary" href="#" role="button">Read More »</a></p>
</div>
<?php
}
?>
Every time I run this code though.. It just enters only the headline from ID 1 everytime. and it makes a ton of duplicate post..
I want it to select through all the headlines in that type.. thats why im using the WHILE()
Please try this:
$stmt = $con->prepare("SELECT * FROM news WHERE type = 'sports'");
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach($result as $rfr) {
?>
<div class="row">
<div class="col-lg-4">
<img src="<?php echo $rfr['folder'] . $rfr1['file'];?>.jpg" >
<h2><?php echo $rfr['headline'];?></h2>
<p>V.A. conducts study to determine effectiveness</p>
<p><a class="btn btn-primary" href="#" role="button">Read More »</a></p>
</div>
...
</div>
<?php } ?>
Why don't you just use a foreach? That way you don't have to worry about handling iterations and possible infinite loops that while loops have.
Also, I personally prefer not to make function calls and assignments in a while/foreach.. It's not that big of a deal to add 1 extra line just before the declaration. Will improve readability and make it easier to debug your code.

Categories