Echo datas from an array with php - php

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

Related

resume foreachloop after incrementing php bootstrapp drop down menu

Question in short: i want to output array: 0, 1 , 2 then break, echo something , output 3,4,5 and keep this in a loop.
Hello everyone i am working on a dynamic php website with bootstrap 4 and php to practice the language. Unfortunately i am now stuck since i dont know how to create something that kindoff looks like an algorith. Allright enough talking and lets get down to the code:
nav.php file
<ul class="navbar-nav">
<li class='nav-item dropdown'>
<a class='nav-link dropdown-toggle' data-toggle='dropdown' datatarget='dropdown_target' href='#'>
<span class='caret'></span>Dropdown
</a>
<div class="dropdown-divider"></div>
<div class="dropdown-menu" aria-labelledby="dropdown_target">
<!-- <a class="dropdown-item">Dropdown</a> -->
<?php
$i=0;
foreach ($dropItems as $item ) {
echo "<a class='dropdown-item' href=\"$item[slug]\">$item[title] </a>";
$i++;
if($i==1) break;
echo "<a class='dropdown-item'>Dropdown</a>";
}
?>
</div>
</li>
</li>
<?php
foreach ($navItems as $item ) {
echo "<li class='nav-item'> <a class='nav-link' href=\"$item[slug]\">$item[title]</a> </li>";
}
?>
</ul>
arrays.php
<?php
//Navigatie menu items
$navItems = array(
array(
"slug" => "index.php",
"title" => "home"
),
array(
"slug" => "contact.php",
"title" => "Contact"
),
array(
"slug" => "market.php",
"title" => "Marketplace"
),
);
$dropItems = array(
array(
"slug" => "#",
"title" => "Lps"
),
array(
"slug" => "#",
"title" => "Sps"
),
array(
"slug" => "market.php",
"title" => "Marketplace"
),
);
?>
You can use array_chunk to split the array in the chunks of three and foreach nested with echo "something";.
Can't see in your code where this echo of three is so I just made an example of how to do it.
$arr = range(1,12); //example array
$chunks = array_chunk($arr, 3);
Foreach($chunks as $chunk){
Foreach($chunk as $val){
Echo $val ." ";
}
Echo "\nsomething\n";
}
https://3v4l.org/0VlN0
Thanks to Andreas i got it working using his method
$chunks = array_chunk($dropItems, 2);
Foreach($chunks as $chunk){
Foreach($chunk as $item){
echo "<a class='dropdown-item' href=\"$item[slug]\">$item[title] </a>";
}
Echo "<div class='dropdown-divider'></div>";
}

PHP: Help in Retrieving and Echoing Multidimensional Array ID

I'm looking to display a list of available weapons of a game, based on items listed in an array. I'm able to display information suck as 'Attribute Values' and 'Price' perfectly via a foreach loop, however being a PHP newbie, I'm having a lot of trouble working out how to echo each item's ID, such as 'Short Sword', 'Middle Sword', 'Long Sword', etc. I thought I was getting close using key($sword)... but no dice. Here's what I'm working with:
<?php $item_swords = Array();
$item_swords["Short Sword"] = Array (
"Attribute Value" => 5,
"Price" => 100,
);
$item_swords["Middle Sword"] = Array (
"Attribute Value" => 8,
"Price" => 250,
);
$item_swords["Long Sword"] = Array (
"Attribute Value" => 12,
"Price" => 750,
); ?>
<?php foreach ($item_swords as $sword) { ?>
<li>
<img src="<?php echo $sword["Item Sprite"]; ?>">
<span><?php echo $sword; ?></span>
<div>ATT +<?php echo $sword["Attribute Value"]; ?></div>
<div><?php echo $sword["Price"]; ?>G</div>
</li>
<?php } ?>
If anyone could lend a hand and help demonstrate how best to echo an item's ID or a per item basis throughout my loop, then that would be very awesome indeed. Thank you for your time.
try with this code
use key attr in foreach loop
and echo $key value instead of array like $sword
<?php $item_swords = Array();
$item_swords["Short Sword"] = Array (
"Attribute Value" => 5,
"Price" => 100,
);
$item_swords["Middle Sword"] = Array (
"Attribute Value" => 8,
"Price" => 250,
);
$item_swords["Long Sword"] = Array (
"Attribute Value" => 12,
"Price" => 750,
); ?>
<?php foreach ($item_swords as $key=>$sword) { ?>
<li>
<img src="
<?php //echo $sword["Item Sprite"]; ?>">
<span><?php echo $key; ?></span>
<div>
ATT +
<?php echo $sword["Attribute Value"]; ?></div>
<div>
<?php echo $sword["Price"]; ?>G
</div>
</li>
<?php } ?>

Foreach not showing all items in multidimensional array

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>

PHP Array Iterator to DIV

I want to loop through the unknown depth array with RecursiveIteratorIterator in SELF::FIRST mode along with RecursiveArrayIterator.
If the array value is an array, I will open a DIV so the "subarray" will be inside this DIV. Something like
$array = array(
'key0' => '0',
'key1' => array(
'value0' => '1',
'value1' => '2',
),
'key2' => '3',
'key3' => array(
'value2' => '4',
'value3' => array(
'value4' => '5'
),
'value4' => array(
'value5' => '6'
),
),
);
Then the HTML should be:
<div>
<div>
<p>key0 is 0</p>
</div>
<div>
<p>key1</p>
<div>
<p>value0 is 1</p>
<p>value1 is 2</p>
</div>
</div>
<div>
<p>key2 is 3</p>
</div>
<div>
<p>key3</p>
<div>
<p>value2 is 4</p>
<p>value3</p>
<div>
<p>value4 is 5</p>
</div>
<p>value4</p>
<div>
<p>value5 is 6</p>
</div>
</div>
</div>
</div>
But the problem is my code can only close 1 <div> tag each time. I have no idea how to remember how deep was there. So I can close to a for loop and echo </div>.
My current code:
<?php
echo '<div>';
$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($iterator_array), RecursiveIteratorIterator::SELF_FIRST);
$is_start = true;
$last_element = '';
foreach($iterator as $key => $value) {
if(is_array($value) && $is_start) {
echo '<div><p>' . $key . '</p>';
$is_start = false;
$last_element = end($value);
} elseif(is_array($value) && !$is_start) {
echo '</div><div><p>' . $key . '</p>';
$last_element = end($value);
} elseif(!is_array($value)) {
echo '<div><p>' . $key . ' is ' . $value . '</p></div>';
if($last_element == $value) {
echo '</div>';
}
}
}
echo '</div>';
?>
Use this recursive function
May be it will help you
get_div($array);
function get_div($arr) {
foreach($arr as $k => $a){
echo '<div>';
if(is_array($a)) {
echo "<p>".$k."</p>";
get_div($a);
} else {
echo "<p>".$k." is ".$a."</p>";
}
echo '</div>';
}
}

How do I merge same array without show it duplicate

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.

Categories