I want to echo multi-dimensional array by using foreach loop - php

<?php
$StudScore = array(
"Mary" => array(
"physics" => 35,
"maths" => 30,
"chemistry" => 39
),
"Tom" => array(
"physics" => 30,
"maths" => 32,
"chemistry" => 29
),
"Jon" => array(
"physics" => 31,
"maths" => 22,
"chemistry" => 39
)
);
foreach ($StudScore as $key => $value) {
echo "<li>$key</li>";
if (is_array($value)) {
echo "<ul>";
echoArray($value);
echo "</ul>";
} else {
echo "<ul><li>$value</li></ul>";
}
}
?>
Till now i have tried to print array but i am getting below error kindly help me out with this .
Output :
Mary
Fatal error: Call to undefined function echoArray()
i want it to be print as example:
Mary = physics:35,maths:30,chemistry:39
Tom = physics:30,maths:32,chemistry:29
Jon = physics:31,maths:22,chemistry:39

It has to be either echo var_dump($value); or echo print_r($value); if you want to print the WHOLE array. There is no function called echoArray() in PHP.
When you only want to print ONE key/value from the array, you also have to use echo $value;, since the keys/values are only strings.
See https://www.php.net/manual/en/function.var-dump.php and https://www.php.net/manual/en/function.print-r.php

<?php
foreach ($StudScore as $name => $value) {
echo $name." = ";
foreach ($value as $subject => $marks) {
echo $subject.":".$marks.",";
}
echo "<br/>";
}
?>
Finally i got my answer it give output like :
Mary = physics:35,maths:30,chemistry:39
Tom = physics:30,maths:32,chemistry:29
Jon = physics:31,maths:22,chemistry:39

Related

3d nested array foreach statement issue

I have this array written below, and I know it isnt pretty, sorry. I come to this array structure as it is the only way I could think of when dealing with my post request.
$_POST = array("person" => array(
[1] => array("id" => 1, "name" => "bob"),
[2] => array("id" => 2, "name" => "jim")
)
);
I want to be able to pick "name" from certain "id", so below code is what I came up with. In the example below, if person["id"] is equal to 1, retrieve its "name" which is "bob".
foreach ($_POST as $dataSet) {
foreach ($dataSet as $person) {
foreach ($person as $field => $value) {
if ($person["id"] == 1) {
echo $person["name"];
}
}
}
}
The problem I am having is as I execute the code.
the result is bobbob,
it seems like the code looped the if statement twice (same as the number of elements in the person array). I know if I put break into the code, then it will solve it, but anyone know why it looped twice? Maybe this will deepen my foreach and array understanding.
There is no need to have third nested loop. Hope this one will be helpful.
Problem: In the third loop you were iterating over Persons: array("id" => 1, "name" => "bob") which have two keys. and you are checking only single static key $person["id"], that's why it was printing twice.
Solution 1:
Try this code snippet here
<?php
ini_set('display_errors', 1);
$POSTData = array("person" => array(
1 => array("id" => 1, "name" => "bob"),
2 => array("id" => 2, "name" => "jim")
)
);
foreach ($POSTData as $dataSet)
{
foreach ($dataSet as $person)
{
if ($person["id"] == 1)
{
echo $person["name"];
}
}
}
Solution 2:
Alternatively you can try this single line solution.
Try this code snippet here
echo array_column($POSTData["person"],"name","id")[1];//here 1 is the `id` you want.
You must have seen the other answers, and they have already said that you dont need the 3rd loop. but still if you want to keep the third loop.
you can use this code.
foreach ($_POST as $dataSet) {
foreach ($dataSet as $person) {
foreach ($person as $field => $value) {
if($value == 1){
echo $person['name'];
}
}
}
}
No need of third foreach
<?php
$mainArr = array("person" => array(
1 => array("id" => 1, "name" => "bob"),
2 => array("id" => 2, "name" => "jim")
)
);
foreach ($mainArr as $dataSet) {
foreach ($dataSet as $person) {
if ($person["id"] == 1) {
echo $person["name"];
break;
}
}
}
?>
Live demo : https://eval.in/855386
Although it's unclear why you need to do a POST in this fashion, here's how to get "bob" only once:
<?php
$_POST = array("person" => array(
1 => array("id" => 1, "name" => "bob"),
2 => array("id" => 2, "name" => "jim")
)
);
$arr = array_pop($_POST);
foreach($arr as $a) {
if ($a["id"] == 1) {
echo $a["name"];
}
}
Array_pop() is useful for removing the first element of the array whose value is an array itself which looks like this:
array(2) {
[1]=>
array(2) {
["id"]=>
int(1)
["name"]=>
string(3) "bob"
}
[2]=>
array(2) {
["id"]=>
int(2)
["name"]=>
string(3) "jim"
}
}
When the if conditional evaluates as true which occurs only once then the name "bob" displays.
See live code.
Alternatively, you could use a couple of loops as follows:
foreach ($_POST["person"] as $data) {
foreach ($data as $value) {
if ( $value == 1) {
echo $data["name"],"\n";
}
}
}
See demo
As you mentioned, I want to be able to pick name from certain id, : No need of nested looping for that. You can do like this using array_column and array_search :
$data = array("person" => array(
1 => array("id" => 1, "name" => "bob"),
2 => array("id" => 2, "name" => "jim")
)
);
// 1 is id you want to search for
$key = array_search(1, array_column($data['person'], 'id'));
echo $data['person'][$key + 1]['name']; // $key + 1 as you have started array with 1
Output:
bob
with foreach:
foreach ($data as $dataValue) {
foreach ($dataValue as $person) {
if ($person['id'] === 1) {
echo $person["name"];
}
}
}

Multidimensional Array for() with different numbered elements levels

How would I write a foreach loop that would print off all information with the following multidimensional array without using any functions:
$workers = array(
"Natalie" => array
("First term" => array(
"Subworker" => "Susan",
"Length" => '1900-2000',
"Notes" => "Finished all tasks"),
"Second term" => array(
"Subworker" => "Laura",
"Length" => '1985-1986'),
),
"Laura" => array(
"First term" => array(
"Subworker" => "Sarah",
"Length" => '1999-1992'),
),
"Carolyn" => array(
"First term" => array(
"Subworker" => "Jenny",
"Length" => '1900 -1945',
"Notes" => array
("Finished all tasks",
"Did not finish all tasks",
"Completed partial tasks" )
),
),
"Jacob" => array(
"First term" => array(
"Subworker" => "Danielle",
"Length" => '1993-1994',
"Notes" => "Finished all tasks"),
),
"Jenny" => array(
"First term" => array(
"Subworker" => "Angela",
"Length" => '1999 - 2001'),
"Second term" => array(
"Subworker" => array(
"Paula" => "Let Go",
"Steve" => "Hired"),
"Length" => '1987 - 1999',
"Notes" => "Hired"),
)
);
/****So far I've done the following, but it is not printing out everything. For example, it is not printing out under Jenny, Second term, Subworker Paula and Steve./*****
foreach($workers as $worker => $value) {
foreach ($value as $newkey => $info) {
echo $worker.':<br>'.$newkey.':<br>';
foreach ($value as $newkey) {
echo 'Subworker: '.$newkey["Subkey"].'<BR>';
foreach ($value as $newkey) {
echo 'Length: '.$newkey["Length"].'<BR>';
foreach ($value as $newkey) {
echo 'Notes: '.$newkey["Notes"].'<BR>';
}
}
}
}
}
It is necessary to cross by a function and to make small tests upstream, it is always useful to avoid the return of error in environment of dev. :)
I have to add lists (ul, li) for better one reading
if (is_array($workers) && !empty($workers)) {
echo loopArray($workers);
} else {
echo "<ul><li>".$workers."</li></ul>";
}
function loopArray($array)
{
$result = "";
$result .= "<ul>";
foreach ($array as $item => $value) {
if (is_array($value) && !empty($value)) {
$result .= "<li>".$item;
$result .= loopArray($value)."</li>";
} else {
$result .= "<ul><li>".$item.': '.$value."</li></ul>";
}
}
$result .= "</ul>";
return $result;
}
To print the particular array you've provided, without using functions:
// workers
foreach($workers as $worker => $workerarr) {
echo $worker.":<ul>\n";
// worker terms
foreach ($workerarr as $term => $terminfo) {
echo "<li>$term:<ul>\n";
// term info
foreach ($terminfo as $type => $typevalue) {
echo "<li>$type: ";
// is type value an array?
if ( is_array($typevalue) ) {
// if so, put in list
echo "<ul>\n";
foreach ($typevalue as $label => $value) {
$label = is_int($label)? '': "$label: "; // only print text
echo "<li>$label$value</li>\n";
}
echo "</ul>";
}
// if not...
else {
echo $typevalue;
}
echo "</li>\n";
}
echo "</ul></li>\n";
}
echo "</ul>";
}
Using unordered lists to help display the information in a readable manner. To see with only break tags as in the question, see PHP Sandbox - Original
PHP Sandbox - Unordered Lists

echo array inside array in order

I have this some arrays that look like this,
$array = Array(
'Homer' => Array
(
'id' => 222,
'size' => 12
),
'Bart' => Array
(
'id' => 333,
'size' => 3
)
);
I would like to echo Homer: id is 222, size is 12
then in the next line echo Bart: id is 333, size is 3 using a foreach loop as key and values.
So i basically want to echo all the Simpsons character names which have their id and size next their names.
I tired this but it printed homer too many times and it even used Bart's id and size at one point.
foreach( $array as $billdate => $date) {
foreach( $date as $k => $v) {
echo $billdate; // Prints Homer and bart
foreach($array as $innerArray){
foreach($innerArray as $key => $value){
echo "[". $key ."][". $value ."] <br/>";
}}
}
}
Thanks in advance.
you can try like this:
foreach( $array as $billdate => $date) {
echo $billdate.': id is '.$date['id'].', size is '.$date['size'];
}
Don't use so many foreach ,just think your need loop ...
foreach( $array as $billdate => $date) {
echo $billdate; // Prints Homer and bart
foreach($date as $key => $value){
echo "[". $key ."][". $value ."] <br/>";
}
}

Compare $Variables Results, and then orden in different Ways

Hello i just finish a code where i get like 50 variables... all of them with int values..
I have the variables as separete values, just for this example I will set the variables with the result, BUT the result came from other evaluations and stuff that its fine, cause im already echoing a verified result.
$one = 13
$two = 35
$three = 46
The "item1" appears <?PHP echo $one; ?> times<br />
The "item2" appears <?PHP echo $two; ?> times<br />
The "item3" appears <?PHP echo $three; ?> times<br />
This is fine but,, How can i order the results, in ASC way or DSC , to build a order by...
Thanks so much
This far this is working great
$naturales = array(
$uno => "n1",
$dos => "n2",
$tres => "n3",
$cuatro => "n4",
$cinco => "n5",
$seis => "n6",
$siete => "n7",
$ocho => "n8",
$nueve => "n9",
$diez => "n10",
$once => "n11",
$doce => "n12",
$trece => "n13",
$catorce => "n14",
$quince => "n15",
$dieciseis => "n16",
$diecisiete => "n17",
$dieciocho => "n18",
$diecinueve => "n19",
$veinte => "n20",
$veintiuno => "n21",
$veintidos => "n22",
$veintitres => "n23",
$veinticuatro => "n24",
$veinticinco => "n25",
$veintiseis => "n26",
$veintisiete => "n27",
$veintiocho => "n28",
$veintinueve => "n29",
$treinta => "n30",
$treintayuno => "n31",
$treintaydos => "n32",
$treintaytres => "n33",
$treintaycuatro => "n34",
$treintaycinco => "n35",
$treintayseis => "n36",
$treintaysiete => "n37",
$treintayocho => "n38",
$treintaynueve => "n39",
$cuarenta => "n40",
$cuarentayuno => "n41",
$cuarentaydos => "n42",
$cuarentaytres => "n43",
$cuarentaycuatro => "n44",
$cuarentaycinco => "n45",
$cuarentayseis => "n46",
$cuarentaysiete => "n47",
$cuarentayocho => "n48",
$cuarentaynueve => "n49",
$cincuenta => "n50",
$cincuentayuno => "n51",
$cincuentaydos => "n52",
$cincuentaytres => "n53",
$cincuentaycuatro => "n54",
$cincuentaycinco => "n55",
$cincuentayseis => "n56",
);
krsort($naturales);
foreach ($naturales as $count => $name) {
echo "The \"$name\" appears $count times<br />";
}
Why my results are like this (Its hidding all the results with 12 (Similar count results)
for example for "n3" appears 12 times. and its not listed.
The "n20" appears 12 times
The "n30" appears 11 times
The "n37" appears 10 times
The "n41" appears 9 times
The "n42" appears 8 times
The "n45" appears 7 times
The "n47" appears 6 times
The "n35" appears 5 times
The "n44" appears 4 times
The "n46" appears 2 times
The "n56" appears 0 times
Build an array
$myresults = array("Item1"=>13,"item2"=>35,"item3"=>46);
then use asort() or arsort() on the array $myresults
then do a for/foreach loop to output the results
basic guidelines but off this you should be able to google how to implement in detail fairly easily (even on here will work)
$one = 13;
$two = 35;
$three = 46;
$arr = array("Item 1"=>$one,"Item 2"=>$two,"Item 3"=>$three);
echo "<strong>Original</strong><br />";
foreach($arr as $k => $v){
echo $k . " = " . $v . "<br />";
}
asort($arr);
echo "<strong>Ascending Sort</strong><br />";
foreach($arr as $k => $v){
echo $k . " = " . $v . "<br />";
}
arsort($arr);
echo "<strong>Descending Sort</strong><br />";
foreach($arr as $k => $v){
echo $k . " = " . $v . "<br />";
}
As previously mentioned, you can use asort and arsort to sort your array as needed... I'm adding some examples here as well as some working CODE
As mentioned, you could insert your values into an associative array, i.e.:
$items = array(
$one => "item1",
$two => "item2",
$three => "item3"
);
and then you can use a function like ksort() to sort all of your values:
http://php.net/manual/en/function.ksort.php
so you can end up with something like this:
ksort($items);
foreach ($items as $count => $name) {
echo "The \"$name\" appears $count times<br />";
}

PHP compare values in a single array and output the difference

I have an array that looks like this:
$rowarray(
[0] => [PID] => 97162 [TID] => 340 [StatsID] => 49678
[1] => [PID] => 97165 [TID] => 340 [StatsID] => 49673
[2] => [PID] => 97167 [TID] => 340 [StatsID] => 49675
[3] => [PID] => 97162 [TID] => 340 [StatsID] => 49679
)
Then my code looks like this:
$cntr=0;
foreach($rowarray as $row)
{
echo "<tr><td>$row[PID] $row[TID] $row[StatsID] </td></tr>";
$cntr++;
}
Two things I want to do I want to be able not print the duplicates in the array but print the additional column that has a different value. So my desired output would look like this.
97162 340 49678 49679
97165 340 49673
97167 340 49675
I started out with the array_unique() but that only returned:
97162 340 49678
Assuming only the StatsID changes (not clear from the question)
$map = array();
foreach($rowarray as $row){
$k = $row["PID"] . '-' . $row["TID"];
if( !isset( $map[$k] ) ){
$map[$k] = array();
}
array_push( $map[$k], $row["StatsId"] );
}
foreach($map as $k=>$v){
$row = explode( '-', $k );
echo "<tr><td>$row[0] $row[1] " . implode( " ", $v ) . " </td></tr>";
}
Here's what I'd do:
Start by sorting the array (using usort to sort by PID, then by TID)
Initialize "last" variables ($last_PID and $last_TID). They will store the respective values in the loop
In the loop, first compare the "current" variables to the "last" ones, if they're the same then just echo the StatsID value.
If they're not the same, output the <tr> (but not the final </tr>, so the first part of the loop can add more StatsID values if necessary)
Still inside the loop, after outputting everything, update the "last" variables.
After the loop, output the final </tr>
This may not be optimal, but I'm pretty sure it'll work.
Transfer the $rowarray structure into a map of maps of arrays, like this:
$rowarray = array(
array('PID' => 97162, 'TID' => 340, 'StatsID' => 49678),
array('PID' => 97165, 'TID' => 340, 'StatsID' => 49673),
array('PID' => 97167, 'TID' => 340, 'StatsID' => 49675),
array('PID' => 97162, 'TID' => 340, 'StatsID' => 49679)
);
$keys = array();
foreach ($rowarray as $row) {
if (!is_array(#$keys[$row['TID']])) {
$keys[$rowarray['TID']] = array();
}
if (!is_array(#$keys[$row['TID']][$row['PID']])) {
$keys[$row['TID']][$row['PID']] = array();
}
$keys[$row['TID']][$row['PID']][] = $row['StatsID'];
}
foreach ($keys as $pid => $pid_arr) {
foreach ($pid_arr as $tid => $tid_arr) {
echo "<tr><td>$tid $pid " . implode(' ', $tid_arr) . "</td></tr>";
}
}
See this code in action
As far as I can tell, the only way to do this would be to loop through the array creating a new unique array as you go.
$unique = array();
foreach ($row as $value)
{
$key = $value['PID'];
if (isset($unique[$key]))
{
$unique[$key]['StatsID'] .= ' ' . $value['StatsID'];
}
else
{
$unique[$key] = $value;
}
}
Now, $unique would give you the results you're looking for and you can loop through the unique array and output your results (I also added your counter if needed):
$count = count($unique);
foreach ($unique as $row)
{
echo "<tr><td>{$row['PID']} {$row['TID']} {$row['StatsID']} </td></tr>";
}

Categories