PHP displaying multidimensional array - php

I have this array similar to this:
$suppliers = array(
'Utility Warehouse' => array('Gas' => array(0,0), 'Electricty' => array(0,0)),
'British Gas' => array('Gas' => array(93,124), 'Electricty' => array(93,124)),
'Eon' => array('Gas' => array(93,124), 'Electricty' => array(93,124))
);
How can display the information as follows
Utility Warehouse
Gas: 0-0 Electricity 0-0
British Gas
Gas: 93-134 Electricity: 93-134
Eon
Gas: 93-124 Electricity: 93-134
You can see how the displayed data corresponds to the data in the array. I've tried this:
foreach($suppliers as $a){
echo $a[0];
}
But this does nothing. CONFUSED!

<?php
foreach($suppliers as $supplier => $category) {
echo $supplier . '<br />';
foreach($category as $cat_name => $values_arr) {
echo $cat_name . ': ' . implode('-', $values_arr) . '<br /><br />';
}
}
?>

you can try:
foreach($suppliers as $name => $value) {
echo $name . "<br />";
foreach($value as $a => $price) {
echo $a .': '. $price[0].'-'.$price[1];
}
echo "<br /><br />";
}

The code to achieve what you want would be following, but i suggest you brush up on your PHP skills a bit more, as this is a trivial task.
foreach($suppliers as $name => $data){
echo $name . '<br/>';
foreach($data as $utility => $value){
echo $utility . ': ' . $value[0] . '-' . $value[1] . ' ';
}
echo '<br/><br/>';
}

Same answer as everyone else (I'm too slow). Here's a working example: http://codepad.org/PDPEjAGJ
Also, everyone who answered this question, me included, is guilty of spoonfeeding. Ahh well, the things I'll do for points! :p

Here is a simple recursive function one can use. I found it and modified it for presentation purposes. The original source is in the comments.
function print_a($array, $level=0){
# source: https://thisinterestsme.com/php-using-recursion-print-values-multidimensional-array/
foreach($array as $key => $value){
# If $value is an array.
if(is_array($value)){
echo str_repeat("-", $level). "<br>{$key}<br>\r\n";
# We need to loop through it.
print_a($value, $level + 1);
} else{
# It is not an array, so print it out.
echo str_repeat("-", $level) . "{$key}: {$value}<br>\r\n";
}
}
} # END FUNCTION print_a

Related

For Each loop with 2 parent 'columns'

I am trying to expand on some working code, and not sure how to do it.
Basicly the information can be under either information or some othertitle.
but i dont care for this split, i just want to do a foreach for all of them together.
Basicly i currently run a for each loop like this:
foreach ($info_array['information'] as $item) {... do something }
Would it be possible to somehow say, For each info_array 'information' & 'othertitle' as $item?
array is structured like:
information
random number
price
amount
total
random number
price
amount
total
othertitle
random number
price
amount
total
random number
price
amount
total
i tried this, but that didnt work:
foreach ($item_array['information'] as $item and $item_array['othertitle'] as $item)
The first idea that comes in mind is just use two loops - first one iterates over $item_array['information'], second one - over $item_array['othertitle']. Something like this:
foreach ($item_array['information'] as $item) {
echo $item['key1'] . ' -> ' . $item['key2'];
}
foreach ($item_array['othertitle'] as $item) {
echo $item['key1'] . ' -> ' . $item['key2'];
}
But, if you do the same output for each element of each array, you can do this:
$keys = ['information', 'othertitle'];
foreach ($keys as $key) {
echo 'Key is ' . $key . '<br />';
foreach ($item_array[$key] as $item) {
echo $item['key1'] . ' -> ' . $item['key2'];
}
}
And even it the output for arrays is different - you can solve it in this way:
$keys = ['information', 'othertitle'];
foreach ($keys as $key) {
echo 'Key is ' . $key . '<br />';
foreach ($item_array[$key] as $item) {
if ('information' === $key) {
echo 'Info: ' . $item['key1'] . ' -> ' . $item['key2'];
} else {
echo 'Ttile: ' . $item['key1'] . ' and ' . $item['key2'];
}
}
}
And if you have to iterate over all subarrays of $item_array, the solution is the same as in #AbraCadaver answer:
foreach ($item_array as $key => $items) {
echo 'Key is ' . $key . '<br />';
foreach ($items as $item) {
if ('information' === $key) {
echo 'Info: ' . $item['key1'] . ' -> ' . $item['key2'];
} else {
echo 'Ttile: ' . $item['key1'] . ' and ' . $item['key2'];
}
}
}
Since you know the indexes you could array_merge or use +:
foreach ($item_array['information'] + $item_array['othertitle'] as $item) {
// do something
}
Otherwise you need two loops:
foreach ($item_array as $array) {
foreach($array as $item) {
// do something
}
}

How to remove first element of an array using loop

I have very little experience with PHP, but I'm taking a class that has PHP review exercises. One of them is to create a function that uses a loop to return all values of an array except the first value in an unordered list. I'm assuming there's a way to do this using a foreach loop but cannot figure out how. This is what I had but I feel like I am far off:
<?php
$array = array('myName' => 'Becca', 'favColor' => 'violet', 'favMovie' => 'Empire Strikes Back', 'favBook' => 'Lullaby', 'favWeb' => 'twitter.com');
$myName = $array['myName'];
$favColor = $array['favColor'];
$favMovie = $array['favMovie'];
$favBook = $array['favBook'];
$favWeb = $array['favWeb'];
echo '<h1>' . $myName . '</h1>';
function my_function() {
foreach($array == $myName){
echo '<ul>'
. '<li>' . $favColor . '</li>'
. '<li>' . $favMovie . '</li>'
. '<li>' . $favBook . '</li>'
. '<li>' . $favWeb . '</li>'
. '</ul>';
}
}
my_function();
?>
The correct syntax of foreach is
foreach (array_expression as $key => $value)
instead of
foreach($array == $myName){
function that uses a loop to return all values of an array except the
first value
I'm not sure, what exactly you mean by except the first value. If you are trying to remove first element from the array. Then you could have used array_shift
If you are supposed to use loop then
$count = 0;
foreach ($array as $key => $value)
{
if ($count!=0)
{
// your code
}
$count++;
}
Change the code to following
<?php
$array = array('myName' => 'Becca', 'favColor' => 'violet', 'favMovie' => 'Empire Strikes Back', 'favBook' => 'Lullaby', 'favWeb' => 'twitter.com');
$myName = $array['myName'];
echo '<h1>' . $myName . '</h1>';
function my_function($array)
{
$count = 0;
echo "<ul>";
foreach($array as $key => $value)
{
if($key != "myName")
{
echo "<li>".$value."</li>";
}
}
echo "</ul>";
}
my_function($array);

PHP - Duplicate <li>'s on foreach

i dont speak english but i will try get it.
My problems is on foreach ($json->mods->$k as $name) { because i'm getting duplicates <li>:
Heres the example:
<ul id="1">
<LI><B>BR:</B>
<LI><B>BR:</B>
<LI><B>BR:</B> Asterixmod, Explanado, Modquack</li>
<br>
<LI><B>DE:</B> Sweetphoenix</li>
<br>
<LI><B>E2:</B>
<LI><B>E2:</B> Irishcow, Welshnutter</li>
</ul>
CODE:
<?php
echo '<ul id="1">';
$link = '.json';
$f = file_get_contents($link);
$json = json_decode($f);
if (empty($json)) {
echo '<li id="ere"><B>ERROR</B></li>';
} else {
foreach ($json as $key => $val) {
foreach ($val as $k => $v) {
foreach ($json->mods->$k as $name) {
echo strtoupper('<li><b>' . $k . ':</b> ');
}
echo(implode(', ', $json->mods->$k));
echo '</li><br>';
}
}
echo '</ul>';
}
Hope anyone help me, ty.
The reason you're getting this error is because inside your foreach ($json->mods->$k as $name) you are opening an <li>, however, you're not closing it until after that loop. This means that eg. BR will have 3 opening tags and one closing tag.
Furthermore, you can get the output you want with just 1 loop:
foreach ($json->mods as $key => $val) {
echo '<li><b>' . strtoupper($key) . ':</b> ';
echo implode(', ', $val);
echo '</li><br>';
}
or you could even make the echo one line:
foreach ($json->mods as $key => $val) {
echo '<li><b>' . strtoupper($key) . ':</b> ' . implode(', ', $val) . '</li><br>';
}
Hope this helps!

PHP Foreach Duplicates - GameQ

I am trying to create a game server PHP script using GameQ to work with my XenForo, as there isn't one I like.
I have it nearly working, but I am getting duplicates in the foreach.
Below is the code I have, I have stripped out nearly all the html code, so it is mainly the PHP code.
<?php
require '../GameQ.php';
$servers = array(
array('id' => 'CSGO 1','type' => 'csgo','host' => '130.185.144.100:27015'),
array('id' => 'CSGO 2','type' => 'csgo','host' => '173.199.73.230:27015'),
array('id' => 'Minecraft 1','type' => 'minecraft','host' => '85.236.100.111:28365'),
);
$gq = new GameQ();
$gq->addServers($servers);
$gq->setOption('timeout', 4); // Seconds
$gq->setFilter('normalise');
$results = $gq->requestData();
foreach ($results as $game) {
$game = $game['gq_type'];
echo $game . '<br>';
foreach ($results as $key => $server) {
if ($server['gq_type'] == $game) {
if ($server['gq_joinlink'] !='') {
echo $server['gq_joinlink'] . '<br>';
}
echo $server['gq_hostname'] . '<br>';
echo $server['gq_numplayers'] . '<br>';
echo $server['gq_maxplayers'] . '<br>';
echo $server['gq_mapname'] . '<br>';
echo $server['gq_address'] . '<br>';
echo $server['gq_port'] . '<br><br>';
}
}
echo '<br><hr><br>';
}
?>
This is outputing, but you will see it is outputting a duplicate of the csgo servers.
csgo
steam://connect/130.185.144.100:27015/
[MG-1] Mestro Surf | Beginner - Learn2Surf | High TR | FastDL
14
48
surf_mom
130.185.144.100
27015
steam://connect/173.199.73.230:27015/
RivalTide.com Community Server by GameServers.com
0
30
de_dust
173.199.73.230
27015
csgo
steam://connect/130.185.144.100:27015/
[MG-1] Mestro Surf | Beginner - Learn2Surf | High TR | FastDL
14
48
surf_mom
130.185.144.100
27015
steam://connect/173.199.73.230:27015/
RivalTide.com Community Server by GameServers.com
0
30
de_dust
173.199.73.230
27015
minecraft
Welcome to a Multiplay Server!
0
8
world
85.236.100.111
28365
Can anyone help.
Thanks
You are looping over the same array twice:
foreach ($results as $game) {
and
foreach ($results as $key => $server) {
I think the second loop should be
foreach ($game as $key => $server) {
Edit
Taking the second foreach out of the code:
foreach ($results as $server) {
$game= $server['gq_type'];
echo $game. '<br>';
if ($server['gq_type'] == $game) {
if ($server['gq_joinlink'] !='') {
echo $server['gq_joinlink'] . '<br>';
}
echo $server['gq_hostname'] . '<br>';
echo $server['gq_numplayers'] . '<br>';
echo $server['gq_maxplayers'] . '<br>';
echo $server['gq_mapname'] . '<br>';
echo $server['gq_address'] . '<br>';
echo $server['gq_port'] . '<br><br>';
}
echo '<br><hr><br>';
}
That will stop it echoing twice.

eliminate a specified post data on a post request array

I use this code to retrieve all the post request (refer below)
<?php
foreach ($_POST as $key => $value) {
$body .= $key . ": " . $value . '<br>';
}
echo $body;
?>
and there is a post data named "adminemail" and "cat", now what i want is to eliminate those two and print all the post data except those two. How to do that? any suggestions, recommendations and ideas, would love to hear. Thank you in advance.
option 1
unset($_POST['adminemail'],$_POST['cat']);
option 2
<?php
foreach ($_POST as $key => $value) {
if(!in_array($key,array('adminemail','cat'))){
$body .= $key . ": " . $value . '<br>';
}
}
echo $body;
?>
The following should work:
<?php
$arr = array_diff_key($_POST, array("adminemail" => 0, "cat" => 0));
$body = ""; // You must have this line, or PHP will throw an "Undefined variable" notice
foreach($arr as $key => $value){
$body .= $key . ": " . $value . "<br/>";
}
echo $body;
?>

Categories