iterate associate array in php does not print out values - php

I'm trying out the following code for arrays in php, I create a associate array, print out the values and add one more to the array - print out again. This works, but if I try the foreach ($MovieCollection as $key => $value) it does not print out the values. Why does it not do that?
$myArray = array("Star Wars", "The Shining");
foreach ($myArray as $val)
{
echo("Movie: " . $val ."<br>");
}
$MovieCollection = array();
$MovieCollection[] = array('title' => 'Star Wars', 'description' =>'classic');
foreach ($MovieCollection as $film )
{
echo($film['title'] .": " . $film['description'] ."<br>");
}
$MovieCollection[] = array('title' => 'The shinning', 'description' =>'creepy');
foreach ($MovieCollection as $film )
{
echo($film['title'] .": " . $film['description'] ."<br>");
}
echo("<br><br>");
// This does not print the values?
foreach ($MovieCollection as $key => $value)
{
echo($key .": " . $value ."<br>");
}

That is because in this part $MovieCollection is an array of arrays and if you want to echo the $value which is an array, you will do an Array to string conversion which does not work.
What you might do is use another foreach to show the values per array:
foreach ($MovieCollection as $value) {
foreach ($value as $k => $v) {
echo($k .": " . $v ."<br>");
}
}
See a Php demo

Related

how to get multidimensional array output

I have 3 arrays
$description[$cat_id][$kit_id][$item_id] = $description ;
$description2[$cat_id][$kit_id][$item_id] = $description2 ;
$qty_total[$cat_id][$kit_id][$item_id] = $qty;
foreach ($qty_total AS $key => $val) {
echo "Cat: ".$key."<br />";
foreach ($val AS $kkey => $kval) {
echo " Kit: ".$kkey."<br />";
foreach ($kval AS $ikey => $ival) {
echo " Item: ".$ikey." - ".$ival."<br />";
}
}
}
This brings only qty.
My question is how to get qty, description, description2 for given [cat_id][kit_id][item_id]?
You need to use keys of all foreach() loop to access other variables value
foreach ($qty_total AS $key => $val) {
foreach ($val AS $kkey => $kval) {
foreach ($kval AS $ikey => $ival) {
echo $ival;
echo PHP_EOL;
echo $description2[$key][$kkey][$ikey];
echo PHP_EOL;
echo $description[$key][$kkey][$ikey];
}
}
}
Sample output: https://3v4l.org/9uYfT

php associative array: no array build with key from variable name

this code works as expected
$fruits = array("d" => "Zitrone", "b" => "Banane", "c" => "Apfel");
$fruits["a"] = "Orange";
//print_r($fruits);
ksort($fruits);
foreach ($fruits as $key => $val) {
echo "$key = $val\n";
}
ok, now I would like to do the same programmatically:
$collection = array();
foreach ($xml->abschnitte[0]->abschnitt as $sec) {
//echo $sec['strecke']; // this works, the strings are printed out
$collection[$sec['strecke']] = $sec['id'];
}
//print_r($collection); // nothing to see here
//ksort($collection);
foreach ($collection as $key => $val) {
echo $key . " = " . $val . "\n";
}
it seems that there no collection will be build. but there must be a way to build the key up from variables. what do i miss? thanks in advance, mischl

How to get the $key from a multidimentional array using php?

Below is a simple array that I created:
$colors = array(
"parent1" =>array(
"item1"=>"red",
"item2"=>"green",
"item3"=>"blue",
"item4"=>"yellow"
),
"parent2" =>array(
"item1"=>"red",
"item2"=>"green",
"item3"=>"blue",
"item4"=>"yellow"
)
);
What I need to get is the key of my level 1 arrays which are string "parent1" and "parent2".
Currently I'm using foreach with while loop to get the key
foreach ($colors as $valuep) {
while (list($key, $value) = each($colors)) {
echo "$key<br />";
}
}
but I'm only able to get the "parent2" string from using the above method and not "parent1".
You're so close.
foreah($colors as $key => $val)
{
echo $key . "<br/>";
}
Use the key like so:
foreach ($colors as $key => $value) {
echo $key.'<br>';
}
To print out the keys:
foreach ($colors as $key => $value) {
echo $key . '<br />';
}
You can also get all of the keys from an array by using the array_keys() method, for example:
$keys = array_keys($colors);
foreach ($keys as $key) {
echo $key . '<br />';
}

PHP Merge Similar Objects In A Multidimensional Array

I have a multidimensional array in PHP, something that looks like:
array(array(Category => Video,
Value => 10.99),
array(Category => Video,
Value => 12.99),
array(Category => Music,
Value => 9.99)
)
and what I would like to do is combine similar categories and output everything into a table, so the output would end up being:
<tr><td>Video</td><td>23.98</td></tr>
<tr><td>Music</td><td>9.99</td></tr>
Any suggestions on how to do this?
EDIT:
I can have these in two different arrays if that would be easier.
A simple loop will do:
$array = [your array];
$result = array();
foreach ($array as $a) {
if (!isset($result[$a['Category']])) {
$result[$a['Category']] = $a['Value'];
} else {
$result[$a['Category']] += $a['Value'];
}
}
foreach ($result as $k => $v) {
echo '<tr><td>' . htmlspecialchars($k) . '</td><td>' . $v . '</td></tr>';
}
$result = array();
foreach ($array as $value) {
if (isset($result[$value['Category']])) {
$result[$value['Category']] += $value['Value'];
} else {
$result[$value['Category']] = $value['Value'];
}
}
foreach ($result as $category => $value) {
print "<tr><td>$category</td><td>$value</td></tr>";
}

Print $_POST variable name along with value

I have a POST in PHP for which I won't always know the names of the variable fields I will be processing.
I have a function that will loop through the values (however I would also like to capture the variable name that goes with it.)
foreach ($_POST as $entry)
{
print $entry . "<br>";
}
Once I figure out how to grab the variable names, I also need to figure out how I can make the function smart enough to detect and loop through arrays for a variable if they are present (i.e. if I have some checkbox values.)
If you just want to print the entire $_POST array to verify your data is being sent correctly, use print_r:
print_r($_POST);
To recursively print the contents of an array:
printArray($_POST);
function printArray($array){
foreach ($array as $key => $value){
echo "$key => $value";
if(is_array($value)){ //If $value is an array, print it as well!
printArray($value);
}
}
}
Apply some padding to nested arrays:
printArray($_POST);
/*
* $pad='' gives $pad a default value, meaning we don't have
* to pass printArray a value for it if we don't want to if we're
* happy with the given default value (no padding)
*/
function printArray($array, $pad=''){
foreach ($array as $key => $value){
echo $pad . "$key => $value";
if(is_array($value)){
printArray($value, $pad.' ');
}
}
}
is_array returns true if the given variable is an array.
You can also use array_keys which will return all the string names.
You can have the foreach loop show the index along with the value:
foreach ($_POST as $key => $entry)
{
print $key . ": " . $entry . "<br>";
}
As to the array checking, use the is_array() function:
foreach ($_POST as $key => $entry)
{
if (is_array($entry)) {
foreach($entry as $value) {
print $key . ": " . $value . "<br>";
}
} else {
print $key . ": " . $entry . "<br>";
}
}
It's much better to use:
if (${'_'.$_SERVER['REQUEST_METHOD']}) {
$kv = array();
foreach (${'_'.$_SERVER['REQUEST_METHOD']} as $key => $value) {
$kv[] = "$key=$value";
}
}
If you want to detect array fields use a code like this:
foreach ($_POST as $key => $entry)
{
if (is_array($entry)){
print $key . ": " . implode(',',$entry) . "<br>";
}
else {
print $key . ": " . $entry . "<br>";
}
}

Categories