This is my first question in a long time, any help is greatly appreciated!
I've got one database storing vehicles and one database storing their images. I am using an INNER JOIN to grab a list of vehicles and their images. After the database query, I put the return into an array; so 2 arrays in 1 array:
return array($vehicles, $vehicle_images);
When I do a print_r I get the correct return:
<?php print_r($your_listings[0]); ?>
<br />
<?php print_r($your_listings[1]); ?>
Returns:
Array
(
[0] => Array
(
[vehicle_id] => 35
[vehicle_type] => jeep
[vehicle_vin] => 6969
[owner_email] => user#user.com
[vehicle_make] => Jeep
[vehicle_year] => 2008
[vehicle_model] => cherokee
)
[1] => Array
(
[vehicle_id] => 36
[vehicle_type] => motorcycle
[vehicle_vin] => 1234
[owner_email] => user#user.com
[vehicle_make] => honda
[vehicle_year] => 2018
[vehicle_model] => random
)
[2] => Array
(
[vehicle_id] => 39
[vehicle_type] => atv
[vehicle_vin] => 3215
[owner_email] => user#user.com
[vehicle_make] => Yamaha
[vehicle_year] => 1990
[vehicle_model] => OHYEA
)
)
Array
(
[0] => Array
(
[vehicle_id] => 35
[image_display] => placeholder
)
[1] => Array
(
[vehicle_id] => 36
[image_display] => /new/images/vehicles/users/42/image.jpg
)
[2] => Array
(
[vehicle_id] => 36
[image_display] => /new/images/vehicles/users/42/vehicle1.jpg
)
[3] => Array
(
[vehicle_id] => 35
[image_display] => /new/images/vehicles/users/42/vehicle.jpg
)
[4] => Array
(
[vehicle_id] => 39
[image_display] => placeholder
)
)
Now when I do a foreach (including bootstrap 4 styling), it only shows 2 vehicles instead of 3; the 2 vehicles it shows appear to be showing exactly as I want them:
<div class="container-fluid">
<div class="row no-gutters">
<?php
$your_listings = owner_listings($_SESSION['user']);
if (!($your_listings[0])) {
echo '<div class="col-sm"><div class="alert alert-danger" role="alert"><i class="fas fa-exclamation"></i> You do not have any listings active at this time.</div></div>';
}
else {
foreach ($your_listings as $i => $item) {
$make = $your_listings[0][$i]['vehicle_make'];
$model = $your_listings[0][$i]['vehicle_model'];
$year = $your_listings[0][$i]['vehicle_year'];
$vehicle = $your_listings[0][$i]['vehicle_id'];
$image = $your_listings[1][$i]['image_display'];
if ($image != 'placeholder') {
echo '<div class="col-sm"><div class="card" style="width: 18rem;">
<h5 class="card-title text-center font-weight-bold">'.$year.' '.$make.' '.$model.'</h5>
<img class="card-img-top" src="'.$image.'" alt="'.$year.' '.$make.' '.$model.'">
<div class="card-body">
Edit
</div>
</div></div>';
}
else {
if ($your_listings[0][$i]['vehicle_type'] == 'atv') {
$image = '/new/images/vehicles/types/atv.png';
}
elseif ($your_listings[0][$i]['vehicle_type'] == 'jeep') {
$image = '/new/images/vehicles/types/jeep.png';
}
elseif ($your_listings[0][$i]['vehicle_type'] == 'motorcycle') {
$image = '/new/images/vehicles/types/motorchycle.png';
}
echo '<div class="col-sm"><div class="card" style="width: 18rem;">
<h5 class="card-title text-center font-weight-bold">'.$year.' '.$make.' '.$model.'</h5>
<img class="card-img-top" src="'.$image.'" alt="'.$year.' '.$make.' '.$model.'">
<div class="card-body">
Edit
</div>
</div></div>';
}
}
}
?>
</div>
</div>
Have I just been staring at this too long? What am I doing wrong? Any help is appreciated.
Thanks!
You are looping original array which has two arrays as you said. What you want is to loop through only first element of your_listings array to get three vehicles
if (!($your_listings[0])) {
echo '<div class="col-sm"><div class="alert alert-danger" role="alert"><i class="fas fa-exclamation"></i> You do not have any listings active at this time.</div></div>';
}
else {
foreach ($your_listings as $i => $item) { // should be foreach ($your_listings[0] as $i => $item) {
$make = $item['vehicle_make'];
$model = $item['vehicle_model'];
Give a try to this answer...
<div class="container-fluid">
<div class="row no-gutters">
<?php
$your_listings = owner_listings($_SESSION['user']);
if (!($your_listings[0]))
{
echo '<div class="col-sm"><div class="alert alert-danger" role="alert"><i class="fas fa-exclamation"></i> You do not have any listings active at this time.</div></div>';
}
else
{
$newarray = array();
foreach($your_listings[0] as $i => $item)
{
$newarray[$item["vehicle_id"]] = $item["image_display"];
}
foreach ($your_listings[0] as $i => $item)
{
$make = $item['vehicle_make'];
$model = $item['vehicle_model'];
$year = $item['vehicle_year'];
$vehicle = $item['vehicle_id'];
$image = $newarray[$vehicle];
if ($image != 'placeholder')
{
echo '<div class="col-sm"><div class="card" style="width: 18rem;">
<h5 class="card-title text-center font-weight-bold">'.$year.' '.$make.' '.$model.'</h5>
<img class="card-img-top" src="'.$image.'" alt="'.$year.' '.$make.' '.$model.'">
<div class="card-body">
Edit
</div>
</div></div>';
}
else
{
if ($item['vehicle_type'] == 'atv') {
$image = '/new/images/vehicles/types/atv.png';
}
elseif ($item['vehicle_type'] == 'jeep') {
$image = '/new/images/vehicles/types/jeep.png';
}
elseif ($item['vehicle_type'] == 'motorcycle') {
$image = '/new/images/vehicles/types/motorchycle.png';
}
echo '<div class="col-sm"><div class="card" style="width: 18rem;">
<h5 class="card-title text-center font-weight-bold">'.$year.' '.$make.' '.$model.'</h5>
<img class="card-img-top" src="'.$image.'" alt="'.$year.' '.$make.' '.$model.'">
<div class="card-body">
Edit
</div>
</div></div>';
}
}
}
?>
</div>
</div>
Related
Let's say I have this HTML:
<div class="area">Area One</div>
<div class="key">AAA</div>
<div class="value">BBB</div>
<div class="key">CCC</div>
<div class="value">DDD</div>
<div class="key">EEE</div>
<div class="value">FFF</div>
<div class="area">Area Two</div>
I want to use XPath to make an array:
my_array['area']
[0] =>
['AAA'] => "BBB"
['CCC'] => "DDD"
['EEE'] => "FFF"
[1] => ...
And so on. Any thoughts on how this can be accomplished? What I'm trying to do is use "area" as the marker between sub-arrays.
My knowledge is somewhat limited in PHP but you can try :
<?php
$html = <<<'HTML'
<div class="area">Area One</div>
<div class="key">AAA</div>
<div class="value">BBB</div>
<div class="key">CCC</div>
<div class="value">DDD</div>
<div class="key">EEE</div>
<div class="value">FFF</div>
<div class="area">Area Two</div>
<div class="key">GGG</div>
<div class="value">HHH</div>
<div class="key">III</div>
<div class="value">JJJ</div>
<div class="key">KKK</div>
<div class="value">LLL</div>
HTML;
$document = new DOMDocument();
$document->loadHTML($html);
$xpath = new DOMXpath($document);
$nbarea = count($xpath->query('//*[contains(text(),"Area")]'));
$i=1;
$j=1;
for ($a = 1; $a <= $nbarea; $a++) {
for ($b = 1; $b <= 3; $b++) {
$element1 = $xpath->query('//*[contains(text(),"Area")]['.$i.']/following::div['.$j.']');
$j++;
$element2 = $xpath->query('//*[contains(text(),"Area")]['.$i.']/following::div['.$j.']');
$h1 = $element1->item(0)->nodeValue;
$h2 = $element2->item(0)->nodeValue;
$area[$i-1][$h1] = $h2;
$j++;
}
$i++;
$j=1;
}
print_r($area)
?>
Output :
Array
(
[0] => Array
(
[AAA] => BBB
[CCC] => DDD
[EEE] => FFF
)
[1] => Array
(
[GGG] => HHH
[III] => JJJ
[KKK] => LLL
)
)
Side note : I've assumed you always have the same number of elements for each area (=3).
As per title, I have a problem when adding products to the cart: it would show a window message that says that the product has been added, but in truth it is not there. It gives the following error:
Fatal error: Cannot use object of type stdClass as array
the line is: <td><?php echo $value['item_name']; ?></td>
Here is the code file reserve.php :
<?php
session_start();
ini_set('display_errors', 1);
$connect = mysqli_connect('127.0.0.1', 'root', '***********', 'Community Garden List');
if (isset($_POST['add'])) {
if (isset($_SESSION['cart'])) {
$item_array_id = array_column($_SESSION['cart'], 'product_id');
if (!in_array($_GET['id'], $item_array_id)) {
$count = count($_SESSION['cart']);
$item_array = array(
'product_id' => $_GET['id'],
'item_name' => $_POST['hidden_name'],
'product_price' => $_POST['hidden_price'],
'item_quantity' => $_POST['quantity'],
);
$_SESSION['cart'][$count] = $item_array;
echo '<script>window.location="reserve.php"</script>';
} else {
echo '<script>alert("Product is already Added to Cart")</script>';
echo '<script>window.location="reserve.php"</script>';
}
} else {
$item_array = array(
'product_id' => $_GET['id'],
'item_name' => $_POST['hidden_name'],
'product_price' => $_POST['hidden_price'],
'item_quantity' => $_POST['quantity'],
);
$_SESSION['cart'][0] = $item_array;
}
}
if (isset($_GET['action'])) {
if ($_GET['action'] == 'delete') {
foreach ($_SESSION['cart'] as $keys => $value) {
if ($value['product_id'] == $_GET['id']) {
unset($_SESSION['cart'][$keys]);
echo '<script>alert("Product has been Removed...!")</script>';
echo '<script>window.location="reserve.php"</script>';
}
}
}
}
?>
?>
html code
<?php
$query = 'SELECT * FROM product ORDER BY serial ASC';
$result = mysqli_query($connect, $query);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_array($result)) {
?>
<div class="col-md-4">
<form method="post" action="reserve.php?action=add&id='.$row['id'].">
<div style="border: 1px solid #eaeaec; margin: -1px 19px 3px -1px; box-shadow: 0 1px 2px rgba(0,0,0,0.05); padding:10px;" align="center">
<img src="<?php echo $row['image']; ?>" class="img-responsive" style="width:100%;>
<h5 class="text-info"><?php echo $row['pname']; ?></h5>
<h5 class="text-danger">€ <?php echo $row['price']; ?></h5>
<h5 class="text-info"><?php echo $row['pdescription']; ?></h5>
<input type="text" name="quantity" class="form-control" value="1">
<input type="hidden" name="hidden_name" value="<?php echo $row['pname']; ?>">
<input type="hidden" name="hidden_price" value="<?php echo $row['price']; ?>">
<input type="hidden" name="hidden_pdescription" value="<?php echo $row['pdescription']; ?>">
<input type="submit" name="add" style="margin-top:5px;" class="btn btn-success" value="Add to Bag">
</div>
</form>
</div>
}
}
?>
<?php
if(!empty($_SESSION["cart"])){
$total = 0;
foreach ($_SESSION["cart"] as $key => $value) {
?>
<tr>
<td><?php echo $value["item_name"]; ?></td>
<td><?php echo $value["item_quantity"]; ?></td>
<td>$ <?php echo $value["product_price"]; ?></td>
<td>
$ <?php echo number_format($value["item_quantity"] * $value["product_price"], 2); ?></td>
<td><a href="Cart.php?action=delete&id=<?php echo $value["product_id"]; ?>"><span
class="text-danger">Remove Item</span></a></td>
</tr>
<?php
$total = $total + ($value["item_quantity"] * $value["product_price"]);
}
?>
<tr>
<td colspan="3" align="right">Total</td>
<th align="right">$ <?php echo number_format($total, 2); ?></th>
<td></td>
</tr>
<?php
}
?>
</table>
</div>
</div>
I've tried print "<pre>"; var_dump($row); exit; after this line: foreach e($_SESSION['cart'] as $key => $value) { and it comes a table with NULL inside. What does that mean?
Before that, i tried to change $value['item_name'] with $value->item_name , and i got the following error:
Notice: Undefined property: stdClass::$item_name in
Will you please help me to understand what's wrong? thank you.
i solve some errors try to assemble the parts in the right places
i put all content modified here you should copy paste parts you need.
<?php
session_start();
ini_set('display_errors', 1);
$connect = mysqli_connect('127.0.0.1', 'root', '******************', 'Community Garden List');
if (isset($_POST['add'])) {
if (isset($_SESSION['cart'])) {
$item_array_id = array_column($_SESSION['cart'], 'product_id');
if (!in_array($_GET['id'], $item_array_id)) {
$count = count($_SESSION['cart']);
$item_array = array(
'product_id' => $_GET['id'],
'item_name' => $_POST['hidden_name'],
'product_price' => $_POST['hidden_price'],
'item_quantity' => $_POST['quantity']//!!!,
);
$_SESSION['cart'][$count] = $item_array;
//echo '<script>window.location="reserve.php"</script>';// do not send content when you use sessions $_SESSION['cart'][0] = $item_array;
} else {
// echo '<script>alert("Product is already Added to Cart")</script>';
//echo '<script>window.location="reserve.php"</script>';
}
} else {
$item_array = array(
'product_id' => $_GET['id'],
'item_name' => $_POST['hidden_name'],
'product_price' => $_POST['hidden_price'],
'item_quantity' => $_POST['quantity']//!!!!!!!!!!!! ? ->,
);
$_SESSION['cart'][0] = $item_array;
}
}
if (isset($_GET['action'])) {
if ($_GET['action'] == 'delete') {
foreach ($_SESSION['cart'] as $keys => $value) {
if ($value['product_id'] == $_GET['id']) {
unset($_SESSION['cart'][$keys]);
echo '<script>alert("Product has been Removed...!")</script>';
echo '<script>window.location="reserve.php"</script>';
}
}
}
}
$query = 'SELECT * FROM product ORDER BY serial ASC';
$result = mysqli_query($connect, $query);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_array($result)) {
die();
$tmimi1=<<<mimi1
<div class="col-md-4">
<form method="post" action="reserve.php?action=add&id={$row['id']}">
<div style="border: 1px solid #eaeaec; margin: -1px 19px 3px -1px; box-shadow: 0 1px 2px rgba(0,0,0,0.05); padding:10px;" align="center">
<img src="{$rr1}" class="img-responsive" style="width:100%;">
<h5 class="text-info">{$row['pname']}</h5>
<h5 class="text-danger">€{$row['price']}</h5>
<h5 class="text-info">{$row['pdescription']}</h5>
<input type="text" name="quantity" class="form-control" value="1">
<input type="hidden" name="hidden_name" value="{$row['pname']}">
<input type="hidden" name="hidden_price" value="{$row['price']}">
<input type="hidden" name="hidden_pdescription" value="{$row['pdescription']}">
<input type="submit" name="add" style="margin-top:5px;" class="btn btn-success" value="Add to Bag">
</div>
</form>
</div>
mimi1;
}
}
echo($tmimi1);
if(!empty($_SESSION["cart"])){
$total = 0;
foreach ($_SESSION["cart"] as $key => $value) {
$tmimi2 =<<<mimi2
<tr>
<td>{$value["item_name"]}</td>
<td>{$value["item_quantity"]}</td>
<td>${$value["product_price"]}</td>
<td>$
mimi2;
echo($tmimi2);
echo number_format($value["item_quantity"] * $value["product_price"], 2);
$tmimi2=<<<mimi3
</td>
<td><a href="Cart.php?action=delete&id={$value["product_id"]}"><span
class="text-danger">Remove Item</span></a></td>
</tr>
mimi3;
echo($tmimi3);
$total = $total + ($value["item_quantity"] * $value["product_price"]);
}
$tmimi2=<<<mimi4
<tr>
<td colspan="3" align="right">Total</td>
<th align="right">$
mimi4;
echo($tmimi4);
echo number_format($total, 2);
$tmimi2=<<<mimi5
</th>
<td></td>
</tr>
mimi5;
echo($tmimi5); }
$tmimi2=<<<mimi6
</table>
</div>
</div>
mimi6;
echo($tmimi6);
?>
you deleted your post about grab an array from online weather data before to post you the answer? i don't know how to send you what you ask and then you delete the question before to push 'post the answer' button!(if was you mimi who ask or there is another mimi=not sure) in case you ask before that i post you the answer:
<?php
function print_r2($var){
echo('<h3>'.$var.':</h3><br>');
print_r($GLOBALS[$var]);echo('br');
}
function hr(){
echo('<hr>');
}
$lines=implode(file('http://samples.openweathermap.org/data/2.5/weather?lat=35&lon=139&appid=b6907d289e10d714a6e88b30761fae22'));
print_r2('lines');hr();
$data = json_decode($lines);
print_r2('data');hr();
print('wind obj:');print_r($data->wind);hr();
print('speed:');print_r($data->wind->speed);hr();
print('deg:');print_r($data->wind->deg);hr();
?>
and on my screen i got ..push RUN CODE SNIPPET!
<h3>lines:</h3><br>{"coord":{"lon":139.01,"lat":35.02},"weather":[{"id":800,"main":"Clear","description":"clear sky","icon":"01n"}],"base":"stations","main":{"temp":285.514,"pressure":1013.75,"humidity":100,"temp_min":285.514,"temp_max":285.514,"sea_level":1023.22,"grnd_level":1013.75},"wind":{"speed":5.52,"deg":311},"clouds":{"all":0},"dt":1485792967,"sys":{"message":0.0025,"country":"JP","sunrise":1485726240,"sunset":1485763863},"id":1907296,"name":"Tawarano","cod":200}br<hr><h3>data:</h3><br>stdClass Object
(
[coord] => stdClass Object
(
[lon] => 139.01
[lat] => 35.02
)
[weather] => Array
(
[0] => stdClass Object
(
[id] => 800
[main] => Clear
[description] => clear sky
[icon] => 01n
)
)
[base] => stations
[main] => stdClass Object
(
[temp] => 285.514
[pressure] => 1013.75
[humidity] => 100
[temp_min] => 285.514
[temp_max] => 285.514
[sea_level] => 1023.22
[grnd_level] => 1013.75
)
[wind] => stdClass Object
(
[speed] => 5.52
[deg] => 311
)
[clouds] => stdClass Object
(
[all] => 0
)
[dt] => 1485792967
[sys] => stdClass Object
(
[message] => 0.0025
[country] => JP
[sunrise] => 1485726240
[sunset] => 1485763863
)
[id] => 1907296
[name] => Tawarano
[cod] => 200
)
br<hr>wind obj:stdClass Object
(
[speed] => 5.52
[deg] => 311
)
<hr>speed:5.52<hr>deg:311<hr>
I have the following array in php:
$stats = array(
"Item 1" => 20,
"Item 2" => 30,
"Item 3" => 66,
"Item 4" => 1
);
I need to echo these values, so I try this:
<?
foreach ($stats as $stat => $data) {
echo '
<div class="col-sm-6">
<div class="widget">
<div class="widget-body p-t-lg">
<div class="clearfix m-b-md">
<h1 class="pull-left text-primary m-0 fw-500"><span class="counter" data-plugin="counterUp">'.$data.'</span></h1>
<div class="pull-right watermark"><i class="fa fa-2x fa-tv"></i></div>
</div>
<p class="m-b-0 text-muted">'.$stats[$stat].'</p>
</div>
</div>
</div>
';
}
?>
But I have only the numerical values echoed.
Do you have the solution ?
Thanks.
Since you are using the foreach construct, $stat holds the keys and $data holds the values. So when saying echo $stats[$stat] is equivalent to echoing the value that has the key $stat. If you want to echo the keys you should do this : echo $stat.
Here you are trying to print the index of the array,
$array = array(0 => 'blue', 1 => 'red', 2 => 'green', 3 => 'red');
$key = array_search('green', $array); // $key = 2;
echo $key;
Use this code to print the key of the array
Hi I would like to know if there is a good algorithm to the search of a substring inside an array that is inside another array,
I have something like:
Array(
[0] => Array(
[0] => img src="1" />
[1] => img src="2" alt="" class="logo i-dd-logo" />
[2] => img src="3" alt="" />
[3] => img src="4" width="21" height="21" alt="" class="i-twitter-xs" />
[4] => img src="myTarget" width="21" height="21" alt="" class="i-rss" />
[5] => <img class="offerimage" id="product-image" src="6" title="" alt=""/>
[6] => <img class="offerimage" id="product-image" src="7" title="" alt=""/>
[7] => <img class="offerimage" id="product-image" src="8" title="" alt=""/>
[8] => <img src="9" width="16" height="16" />
)
[1] => Array(
[0] => src="1"
[1] => src="a" alt="" class="logo i-dd-logo"
[2] => src="b" alt=""
)
)
What I want to do is to know the position of target, for example [0][4] but it's not always the same
What I'm doing now is a while inside another while and checking whith strpos for the substring, but maybe there is a better way to do this, any suggestions?
Thanks for everything
Updated code:
$i=-1;
foreach($img as$outterKey=>$outter) {
foreach($outter as $innerKey=>$inner){
$pos = strpos($img[$outterKey][$innerKey],"myTarget");
if (!$pos === false) {
$i=$outterKey;$j=$innerKey;
break 2;
}
}
}
Umm, maybe like:
foreach($outsideArray as $outterKey=>$outter) {
foreach($outter as $innerKey=>$inner){
if(substr_count ($inner , $needle)) {
echo $outterKey . " and " . $innerKey;
}
}
}
EDIT: Scalable, I noticed in your comments you want it scalable. How about recursive?
function arraySearch($array) {
foreach($array as $key=>$item){
if(is_array($item)
return arraySearch($item);
elseif(substr_count ($item , $needle)
return $key;
}
}
try this code here you got the complete posistion of your string.
here $find is your substring. $data is your array.
$find = "<img src='4' width='21' height='21' alt=' class='i-twitter-xs' />";
foreach ($data as $out_key => $out_value)
{
if(is_array($out_value))
{
if(in_array($find, $out_value))
{
$out_pos = array_search($out_value, $data);
$inn_pos =array_search($find, $out_value);
}
}
}
echo $data[$out_pos][$inn_pos];
I want to merge array which have same key to be one. Example
$options = array(
array("group" => "header","title" => "Content 1"),
array("group" => "header","title" => "Content 2"),
array("group" => "menu","title" => "Content 3"),
array("group" => "content","title" => "Content 4"),
array("group" => "content","title" => "Content 5"),
array("group" => "content","title" => "Content 6"),
array("group" => "footer","title" => "Content 7")
);
foreach ($options as $value) {
if ($value['group']) {
echo "<div class='{$value['group']}'>";
echo $value['title'];
echo "</div>";
}
}
Current output is
<div class='header'>Content 1</div><div class='header'>Content 2</div><div class='menu'>Content 3</div><div class='content'>Content 4</div><div class='content'>Content 5</div><div class='content'>Content 6</div><div class='footer'>Content 7</div>
What I want here is to be
<div class='header'>
Content 1
Content 2
</div>
<div class='menu'>
Content 3
</div>
<div class='content'>
Content 4
Content 5
Content 6
</div>
<div class='footer'>
Content 7
</div>
Let me know
$grouped = array();
foreach($options as $option) {
list($group, $title) = array_values($option);
if (!isset($grouped[$group])) {
$grouped[$group] = array();
}
$grouped[$group][] = $title;
}
foreach ($grouped as $group => $titles) {
echo sprintf('<div class="%s">%s</div>', $group, implode('', $titles));
}
$groups = array ();
foreach ( $options as $value ) {
if ( !isset ( $groups[$value['group']] ) ) {
$groups[]['group'] = $value['group']
}
$groups[$value['group']]['title'][] = $value['title'];
}
foreach ( $groups as $group ) {
echo "<div class="{$group['group']}">";
echo implode ( "\n", $group['title'] );
echo "</div>";
}
This should work, but if it doesn't matter to you, you could also just change the structure of your hardcoded-array, then you wouldn't need my first foreach.