Multidimensional Array - foreach, within a foreach - php

I have a multi dimensional array that is printing out exactly how I want it, however, I have become stuck on figuring out how I can construct it into the for each loop that i'm looking for.
Please Note : $handle is a field the client entered in the backend.
<?php
$gp = Mage::getStoreConfig('social_code/social_group/google_field');
$ld = Mage::getStoreConfig('social_code/social_group/linkedin_field');
$tw = Mage::getStoreConfig('social_code/social_group/twitter_field');
$fb = Mage::getStoreConfig('social_code/social_group/facebook_field');
$social_array = array(
"facebook" => array(
'class' => "facebook",
'url' => 'https://www.facebook.com/',
'handle' => $fb
),
"twitter" => array(
'class' => "twitter",
'url' => 'https://www.twitter.com/',
'handle' => $tw
),
"linked-in" => array(
'class' => "linked-in",
'url' => 'http://www.linkedin.com/company/',
'handle' => $ld
),
"google-plus" => array(
'class' => "google-plus",
'url' => 'https://plus.google.com/',
'handle' => $gp
)
);
?>
Now i wish to spit this out as an unordered list so i have the below, but its still not working for me.
<ul>
<?php foreach ($social_array as $name => $group) :?>
<?php foreach ($group as $class => $url) :?>
<li><?php echo ("$group"); ?></li>
<?php endforeach; ?>
<?php endforeach; ?>
</ul>
I would like it so that it loops through all the social array and prins something similar to this
<li><?php echo $name; ?></li>
or so understood better
<li>Facebook</li>
Also if I'm making this over complicated for myself please let me know.

<ul>
<?php foreach ($social_array as $name => $group) :?>
<li><?php echo $name; ?></li>
<?php endforeach; ?>
</ul>

I think this is what you're looking for if I've understood correctly.
<ul>
<?php foreach ($social_array as $name => $group) :?>
<li><a href="<?php echo $group['url'].$group[handle']; ?>" class="<?php echo $group['class']; ?>"><?php echo $name
<?php endforeach; ?>
</ul>

There is no need to inner foreach.
<?php foreach ($social_array as $name => $group) :?>
<li><?php echo $group['class']; ?></li>
<?php endforeach; ?>

See http://3v4l.org/3cH6f for the example working below. Just one foreach.
<?php
$social_array = array(
"facebook" => array(
'class' => "facebook",
'url' => 'https://www.facebook.com/',
'handle' => 'Mage::getStoreConfig(\'social_code/social_group/twitter_field\')'
),
"twitter" => array(
'class' => "facebook",
'url' => 'https://www.facebook.com/',
'handle' => 'Mage::getStoreConfig(\'social_code/social_group/twitter_field\')'
),
"linked-in" => array(
'class' => "facebook",
'url' => 'https://www.facebook.com/',
'handle' => 'Mage::getStoreConfig(\'social_code/social_group/twitter_field\')'
),
"google-plus" => array(
'class' => "facebook",
'url' => 'https://www.facebook.com/',
'handle' => 'Mage::getStoreConfig(\'social_code/social_group/twitter_field\')'
)
);
$html = '<ul>';
foreach ($social_array as $name => $class_array){
$html .= '<li>'. $name. '</li>';
}
$html .= '</ul>';
print $html;
?>

Give this a shot:
<ul>
<?php foreach ($social_array as $name => $properties) :?>
<li><?php echo ucfirst($name); ?></li>
<?php endforeach; ?>
</ul>
In this foreach, the syntax is foreach($array as $key => $value), so here $name is the key from $social_array, and $properties is the array associated with that key.

The thing you are forgetting is that the inner foreach is processing each item i.e. class,ulr,handle one at a time.
You therefore need to store the information you require as you pass over each of the 3 items so it can be used once you have the 2 items you actually need.
So this may help.
<ul>
<?php
foreach ($social_array as $name => $group) :
$class = NULL;
$url = NULL;
$handle = NULL;
foreach ($group as $name => $value) :
switch ($name) :
case 'class' : $class = $value; break;
case 'url' : $url = $value; break;
case 'handle' : $handle = $value; break;
endswitch;
if ( isset($class) AND isset($url) AND isset($handle) ) :
echo '<li>' . $group . '</li>';
$class = NULL;
$url = NULL;
$handle = NULL;
endif;
endforeach;
endforeach;
?>
</ul>

Related

Display the member of one array depending on the other array

i have an array i and i want to show the array values if the name of same array repeat in the another array and have true value
my arrays like this
$array1 = [
array(
'name' => internal_evidence
'price' => 30
'course_id' => 3
),
array(
'name' => international_evidence
'price' => 450
'course_id' => 3
),
array(
'name' => internal_evidence
'price' => 10
'course_id' => 1
),
array(
'name' => technical_evidence
'price' => 134
'course_id' => 3
),
];
$array2 = [
array(
'id' => 3
'name' => graphic
'price' => 150
'attr' => array(
'internal_evidence' => 'true',
'international_evidence' => 'false',
'technical_evidence' => 'true'
)
),
array(
'id' => 5
'name' => 3dmax
'price' => 300
'attr' => array(
)
),
array(
'id' => 1
'name' => ICDL
'price' => 480
'attr' => array(
'internal_evidence' => 'true',
)
),
];
i want to showing this all attr selected with true value in like this
also I want to sum price of array2 member and array1
<h2>graphic</h2>
<p>internal_evidence</p>
<p>technical_evidence</p>
<small>course price: 150</small>
<small>314</small> <!-- Price with selected evidence -->
<h2>3dmax</h2>
<small>course price: 300</small>
<!-- its not have attr evidence -->
<h2>ICDL</h2>
<p>internal_evidence</p>
<small>course price: 480</small>
<small>490</small> <!-- Price with selected evidence -->
i try this but its don`t work properly
$priceOfAttr = 0;
foreach($array2 as $key => $cat):
echo "<h2>{$cat['name']}</h2>";
foreach($array1 as $pr):
if($pr['course_id'] == $cat['id']):
foreach($cat['attr'] as $m => $optionV):
if($m == $pr['name'] && $optionV == "true"){
echo $m .'<br>';
$priceOfAttr += $pr['price'];
// echo "<small>{$cat['price']}</small><br>";
// echo $cat['price'] + $pr['price']. "<br>";
}
endforeach;
echo $priceOfAttr + $cat['price'] . '<br>';
endif;
endforeach;
echo '<br>';
endforeach;
I'd use a combination array_reduce and array_map to transform your data into what you need, then simply loop over that to display your view:
<?php
// Index your $array1 by [id][name]
$array1ByIdAndName = array_reduce($array1, static function ($byIdAndName, $entry) {
$byIdAndName[$entry['course_id']][$entry['name']] = $entry;
return $byIdAndName;
});
// Transform $array2's `attr` entries into attribute list + compute total price
$array2 = array_map(static function ($entry) use ($array1ByIdAndName) {
$entry['total_price'] = $entry['price'];
$entry['attr'] = array_reduce(array_keys($entry['attr']), static function ($attrs, $attrName) use ($array1ByIdAndName, &$entry) {
if ($entry['attr'][$attrName] === 'true') {
$attrs[] = $attrName;
$entry['total_price'] += $array1ByIdAndName[$entry['id']][$attrName]['price'];
}
return $attrs;
}, []);
return $entry;
}, $array2);
// Display your view
?>
<?php foreach ($array2 as $entry): ?>
<h2><?= $entry['name'] ?></h2>
<?php foreach ($entry['attr'] as $attrName): ?>
<p><?= $attrName ?></p>
<?php endforeach ?>
<small>course price : <?= $entry['price'] ?></small>
<?php if ($entry['total_price'] > 0): ?>
<small><?= $entry['total_price'] ?></small>
<?php endif ?>
<?php endforeach ?>
Demo: https://3v4l.org/nS3Gl

php how to display values form array into ul li

I have an array like this:
$files = array(
array(
'name' => 'Detailed Brief - www.xyz.com.pdf',
'size' => '1.4MB',
),
array(
'name' => 'Pure WordPress theme.zip',
'size' => '735.9KB',
),
array(
'name' => 'Logotype.jpg',
'size' => '94.7KB',
),
);
How can I display the information as follows:
ul - li
Detailed Brief...- pdf(1.4mb)
Pure Wordpress... - zip(735.kb)
Logotype.jpg-(94,7kb)
Any ideas? I'm trying all the time with foreach but it's not working.
It is simple:
<ul>
<?php foreach ($files as $key => $file): ?>
<li><?php echo $file['name'] . ' - ' . $file['size'] ?></li>
<?php endforeach ?>
</ul>
The other answer is not quite what you're looking for. For each iteration of the loop, you want the filename, the file extension, and the file size:
<ul>
<?php
foreach ($files as $key => $file) {
$f = pathinfo($file['name']);
echo '<li>';
echo $f['filename'].' - '.$f['extension'].'('.$file['size'].')';
echo '</li>';
}
?>
</ul>

Multi-Dimensional PHP array – select data from key

Not sure if I titled this question correctly. I'm having some trouble looping over a multi-demensional php array to build some HTML nodes. Here is the array I'm looping over:
$locations = array(
'CityName' => array(
array(
'title' => 'Title',
'phone' => '(555) 555-5555',
'address' => '1234 Fake st.',
'city' => 'Ventura',
'state' => 'CA',
'zip' => '93003',
'url' => 'http://www.google.com/'
),
array(
'title' => 'Title',
'phone' => '(555) 555-5555',
'address' => '1234 Fake st.',
'city' => 'Ventura',
'state' => 'CA',
'zip' => '93003',
'url' => 'http://www.google.com/'
),
),
'CityName2' => array(
array(
'title' => 'Title',
'phone' => '(555) 555-5555',
'address' => '1234 Fake st.',
'city' => 'Ventura',
'state' => 'CA',
'zip' => '93003',
'url' => 'http://www.google.com/'
),
array(
'title' => 'Title',
'phone' => '(555) 555-5555',
'address' => '1234 Fake st.',
'city' => 'Ventura',
'state' => 'CA',
'zip' => '93003',
'url' => 'http://www.google.com/'
)
)
);
Keep in mind I may have built this array incorrectly for what I'm trying to do. The HTML output for this loop should be:
<h4>CityName</h4>
<ul>
<li>
<p>Title</p>
<p>1234 Fake St.</p>
<p>Ventura, CA 93003</p>
<p>(555) 555-5555</p>
<p class="link">Visit Website</p>
</li>
<li>
<p>Title</p>
<p>1234 Fake St.</p>
<p>Ventura, CA 93003</p>
<p>(555) 555-5555</p>
<p class="link">Visit Website</p>
</li>
</ul>
<h4>CityName2</h4>
<ul>
...
</ul>
I think what I want to do is to be able to grab the individual pieces of data to plug into my HTML template.. like $location['title'], $location['phone'], etc. The PHP that I currently have will only go as far to loop over and echo out the keys or values from each individual location array.
<?php
// Printing all the keys and values one by one
$locationNames = array_keys($locations);
for($i = 0; $i < count($locations); $i++) {
echo "<h4>" . $locationNames[$i] . "</h4>";
echo "<ul>";
foreach($locations[$locationNames[$i]] as $key => $value) {
foreach($value as $key => $value) {
echo $value;
}
}
echo "</ul>";
}
?>
Use nested foreach loops amd drop the values in to the appropriate places:
<?php foreach ($locations as $location => $ldata) { ?>
<h4><?php echo $location; ?></h4>
<ul>
<?php foreach ($ldata as $attribute) { ?>
<li>
<p><?php echo $attribute['title']; ?></p>
<p><?php echo $attribute['address']; ?></p>
<p><?php echo $attribute['city'] . " ," . $attribute['state'] . " " . $attribute['zip']; ?></p>
<p><?php echo $attribute['phone']; ?></p>
<p class="link">Visit Website</p>
</li>
<? php } ?>
<?php } ?>
You just need nested (foreach) loops:
<?php foreach($locations as $cityname => $location):?>
<h4><?=$cityname?></h4>
<ul>
<?php foreach($location as $place:?>
<li>
<p><?=$place['title']?></p>
<p><?=$place['phone']?></p>
<!-- etc etc-->
</li>
<?php endforeach;?>
</ul>
<?php endforeach;?>
Something like this should work. I won't implement the HTML for you, but you it should be easy to do. This has the advantage that if you have dynamic keys in the inner array, you won't have to know them before hand.
foreach($locations as $key => $value) {
echo $key, PHP_EOL;
$data = $locations[$key];
$length = count($data);
for($i = 0; $i < $length; $i++) {
$values = $data[$i];
foreach($values as $key2 => $value2)
echo "\t", $key2, ": ", $value2, PHP_EOL;
}
}
Just a few tweaks to your code:
<?php
// Printing all the keys and values one by one
$locationNames = array_keys($locations);
for($i = 0; $i < count($locations); $i++) {
echo "<h4>" . $locationNames[$i] . "</h4>";
echo "<ul>";
foreach($locations[$locationNames[$i]] as $key => $value) {
echo "<li>"; // add list open tag <-- tweak #1
foreach($value as $key => $value) {
echo "<p>$value</p>"; // add paragraph tags <-- tweak #2
}
echo "</li>"; // add list close tag <-- tweak #3
}
echo "</ul>";
}
?>
PHP Sandbox example.

How to call a function for a select box?

Hi I have this function on PHP:
<?php
class ConectorDatos {
static function buscarProductos() {
return array(
'Hom' => array( '1VX' => 649.95 ),
'Sam' => array( 'Note2' => 699.95,
'Gala' => 499.95,
'Gel' => 249.95),
'olivi' => array( 'Lumia' => 999.95),
'Obvow' => array( 'One Plus One' => 299.50 )
);
}
And the HTML Page with this code section:
<div id="productos">
<ul class="telefonoEspecifico">
<li>Marca:</li>
<select name="marc" id="marc4">
<?php
****************
?>
</select>
<li>Modelo:</li>
<li>Precio:</li>
So my question is simple but I don't know how to do it...how HTML on the "select" section could "call" the phpfunction and show the necessary information on webpage. What do I have to do?
You need to include 1st php file in 2nd one like this
<div id="productos">
<ul class="telefonoEspecifico">
<li>Marca:</li>
<select name="marc" id="marc4">
<?php
require("file_name");
$obj = new ConectorDatos();
$data=$obj-> buscarProductos();
foreach($data as $key=>$value)
echo "<option>$key</option>";
?>
</select>
<li>Modelo:</li>
<li>Precio:</li>
<?php
class ConectorDatos {
public static function buscarProductos() {
return array(
'Hom' => array( '1VX' => 649.95),
'Sam' => array( 'Note2' => 699.95,
'Gala' => 499.95,
'Gel' => 249.95),
'olivi' => array( 'Lumia' => 999.95),
'Obvow' => array( 'One Plus One' => 299.50)
);
}
}
?>
Click here for a DEMO
<?php $producto = ConectorDatos::buscarProductos();?>
<div id="productos">
<ul class="telefonoEspecifico">
<li>Marca:<?php echo $producto['Hom']['1VX'];?></li>
<select name="marc" id="marc4">
<?php
echo "<option value='".$producto['Sam']['Note2']."'>".$producto['Sam']['Note2'] . "</option>";
echo "<option value='".$producto['Sam']['Gala']."'>".$producto['Sam']['Gala'] . "</option>";
echo "<option value='".$producto['Sam']['Gel']."'>".$producto['Sam']['Gel'] . "</option>";
?>
</select>
<li>Modelo:<?php echo $producto['olivi']['Lumia'];?></li>
<li>Precio:<?php echo $producto['Obvow']['One Plus One'];?></li>

correct way to display 3 dimensional array with key and value php

I have a 3 dimensional array defined like:
$seccc = array(
array(
"Href" => base_url().'capture/',
"Icono" => base_url().'assets/images/icon_home.png',
"Texto" => 'Captura',
"Submenu" => array(1,2,3)
),
array(
"Href" => base_url().'seg/',
"Icono" => base_url().'assets/images/icon_tra.png',
"Texto" => 'Seg',
"Submenu" => array('ALFA','OMEGAL','DELTA')
),
array(
"Href" => base_url().'usr/',
"Icono" => base_url().'assets/images/icon_users.png',
"Texto" => 'Users',
"Submenu" => ''
),
array(
"Href" => base_url().'clients/',
"Icono" => base_url().'assets/images/icono_gro.png',
"Texto" => 'Clients',
"Submenu" => ''
),
array(
"Href" => base_url().'suc/',
"Icono" => base_url().'assets/images/icupo.png',
"Texto" => 'Suc',
"Submenu" => ''
)
);
I am doing foreach loop like
foreach ($seccc as $part)
{
foreach ($part as $item)
{
echo '<li>'.$item["Href"];
if(is_array($item["Submenu"]))
{
foreach($item["Submenu"] as $subkey)
{
echo '<ul>';
echo $subkey;
echo '</ul>';
}
}
}
echo '</li>';
}
}
However I can not access to "Href", "Icono", "Texto" or "Submenu" items, How to access their values
seems $item["Href"] does not work
foreach ($seccc as $part)
{
// use $part instead of $item, here you can get $part['Icono'], $part['Texto'] etc
echo '<li>'.$part["Href"];
if(is_array($part["Submenu"]))
{
// loop over $part['Submenu'] if it's an array
foreach($part["Submenu"] as $key => $subkey)
{
echo '<ul>';
echo $subkey;
echo '</ul>';
}
}
echo '</li>';
}
You have one loop to many
foreach ($seccc as $item)
{
echo '<li>'.$item["Href"];
if(is_array($item["Submenu"]))
{
foreach($item["Submenu"] as $subkey)
{
echo '<ul>';
echo $subkey;
echo '</ul>';
}
}
}

Categories