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

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

Related

iterate associate array in php does not print out values

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

Confused about how to loop through subArray

First of all I have searched for the similar threads on StackOverflow like this one
$myvar = array ("key_name" => array("tom", "an", "bob"),
"key_age" => array("1", "10", "12")
);
I have tried lot of things but I couldn't
foreach($myvar as $i){
foreach ($i as $key => $value) {
echo print_r($i);
}
I am trying to get "key_name" and loop through it
<?php
$myvar = array (
"key_name" => array("tom", "an", "bob"),
"key_age" => array("1", "10", "12")
);
foreach ($myvar['key_name'] as $value) {
echo $value;
}
Result:
tomanbob
https://3v4l.org/tEFvS
If you want to loop through both:
foreach ($myvar as $sub_array) {
foreach ($sub_array as $value) {
echo $value;
}
}
Result:
tomanbob11012
https://3v4l.org/cMFUh
Check out, http://php.net/manual/en/control-structures.foreach.php for info on using foreach
You can use array_walker. So you can do something like this :
array_walk($myvar,function($sub_items,$key){
echo "Key is >> " . $key . "\n";
foreach($sub_items as $item){
echo $item . "\n";
}
echo "------------ \n ";
});
Note:
I put an echo with a new line to understand how to implement that!

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 />';
}

foreach doesn't print altered array properly

I am trying to print an array using foreach and while printing, if a certain $key comes up, I want to make changes to the array. Problem is, even though the array gets changed, the changes do not get printed.
In the example below, you will find:
function I use to change the array;
an array first printed with no changed;
then echo print-out in with changes during the process - all using foreach;
another print-out of the same table, but this time with changes.
<?php
function insert_before_key($array, $key, $data = NULL){
if (($offset = array_search($key, array_keys($array))) === false){
$offset = count($array);
}
return array_merge(array_slice($array, 0, $offset), (array) $data, array_slice($array, $offset));
}
$array = array(
"no_color" => "blank",
"color1" => "red",
"color2" => "green",
"color3" => "blue",
);
echo "<pre>";
print_r($array);
echo "</pre>";
foreach ($array as $key => $value) {
echo $key . ": " . $value . "<br />";
if ($key === "color1"){
$array = insert_before_key($array, "color2", array("color1.5" => "yellow"));
}
}
echo "<pre>";
print_r($array);
echo "</pre>";
echo "<br />";
?>
Note that the new $key is to jump in AFTER current $key, so I would expect it to come up.
Any idea why this happens ?
EDIT:
Played a bit more with foreach and I think it must be caching the keys or something...
<?php
$test_array = array(0,1,2,3,4,5,6,7,8,9);
foreach ($test_array as $key => $value) {
if ($key === 5){$test_array[7] = $test_array[7]+1;}
echo $key . ": " . $value . "<br />";
}
print_r($test_array);
?>
The above will display UNCHANGED echo, but CHANGED print_r.
From the manual: "As foreach relies on the internal array pointer, changing it within the loop may lead to unexpected behavior." http://php.net/manual/en/control-structures.foreach.php
You shouldn't modify an array you're looping over.
So during iteration you are trying to change the value of the item being iterated
foreach($array ...)
{
change $array
}
Use a copy of $array inside the iteration
$array2 = $array
foreach($array ...)
{
change $array2
}
I'd keep it simple. Something tells me however that you're fixing effects of a problem here and not its source.
$array = array(
"no_color" => "blank",
"color1" => "red",
"color2" => "green",
"color3" => "blue",
);
$temp_array = array();
foreach ($array as $key => $value) {
$temp_array[$key] = $value;
echo $key . ": " . $value . "<br />";
if ($key == 'color1') {
$key_add = 'color1.5';
$value_add = 'yellow';
$temp_array[$key_add] = $value_add;
echo $key_add . ": " . $value_add . "<br />";
}
}
$array = $temp_array;

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>";
}

Categories