Getting Data From Multi-level Array - php

Question below.
This is the solution I came up with based on Pixeler's answer.
<?php
$i = 0;
foreach ($array as $k1 => $v1) {
if (is_array($v1)) {
echo $k1."<br />";
foreach ($v1 as $k2 => $v2) {
echo "--".$k2."<br />----".$v2."<br />";
}
$i++;
}
echo "<br /<br />";
}
?>
<?php
$array = array( "Apples" => array("Red" => "$2.95", "Green" => "$2.45"),
"Oranges" => array("Navel" => "$4.95"),
"Grapes" => array("Purple" => "$3.75", "Green" => "$3.25")
);
?>
Is it possible to take what's above and get the text for each value by calling a number?
How could I do something like this?...
<?php
echo $array[0];
//Outputs "Apples"
echo $array[0][0];
//Outputs "Red"
echo $array[0][0][0];
//Outputs "$2.95"
echo $array[3][2][1];
//Outputs "$3.25" (Grapes > Green > Price)
?>
EDIT: The idea is that I can return the first level (Apples, Oranges, Grapes), second level (Red, Green, Navel, Purple, Green), and third level ($2.95, $2.45, $4.95, $3.75, $3.25) by calling a number.
For example, I want to do something like this:
<?php
count($array); //returns 3 (Apples, Oranges, Grapes)
//Do some for/foreach function that will produce the following:
//Apples
//->Red: $2.95
//->Green: $2.45
//Oranges
//->Navel: $4.95
//Grapes
//Purple: $3.75
//Green: $3.25
//I'm hoping to structure the code like this:
foreach($i = 0; $i =< count($array); $i++){
//echo title of array (Apples)
//echo each child key and it's value (Red: $2.95; Green: $2.45)
foreach($secondcounter = 0; $secondcounter =< count($array[$i]); $secondcounter++){
echo array_key($array[$i][$secondcounter]) . ": " .$array[$i][$secondcounter];
//Note: I don't actually know if array_key does the trick or not, it's meant to return "Red" in this case, while the non array_key()'d is meant to return the price of red apples, $2.95
}
?>
EDIT: It is important to note that I cannot use words to call the data. I must use numbers, i.e. [0] to call the first item in the array, because Apples could change depending on what row of data I load from my database. In other words... Apples could actually turn out to be Books, and Red could turn out to be the name of the book => price.
I'm intending on using serialize/unserialize to store and retrieve the data from the database, although I'm not overly familiar with these functions, I had a brief look at them and they seem reasonably easy to use.
I've been researching for hours but I cant find anything.
It is vital that I am able to call the data by numbers, not text. So $array["Apples"] is unacceptable.
I have also looked at json_decode and serialize/unserialize, and I think I get the basic idea of them from a brief look... but I think my main issue is understanding how to call the above data as presented in my example. Any help would be really great.

This is the solution I came up with based on #Pixeler's answer.
<?php
$i = 0;
foreach ($array as $k1 => $v1) {
if (is_array($v1)) {
echo $k1."<br />";
foreach ($v1 as $k2 => $v2) {
echo "--".$k2."<br />----".$v2."<br />";
}
$i++;
}
echo "<br /<br />";
}
?>

What about this one?
array_search("Apples",array_keys($array));
If you want to loop your array one way or another you might have to create new array, loop through your old array and create new numeric array array?
FIRST WAY
$array = array( "Apples" => array("Red" => "$2.95", "Green" => "$2.45"),
"Oranges" => array("Navel" => "$4.95"),
"Grapes" => array("Purple" => "$3.75", "Green" => "$3.25")
);
$newArray = array();
foreach ($array as $value) {
$newArray[] = (is_array($value)) ? array_values($value) : $value;
}
echo '<pre>';
var_dump($newArray);
echo '</pre>';
SECOND WAY
$array = array( "Apples" => array("Red" => "$2.95", "Green" => "$2.45"),
"Oranges" => array("Navel" => "$4.95"),
"Grapes" => array("Purple" => "$3.75", "Green" => "$3.25")
);
$newArray = array();
$i = 0;
foreach ($array as $key => $value) {
if (is_array($value)) {
$newArray[$i] = array();
foreach ($value as $k => $v) {
$newArray[$i][] = $v;
}
$i++;
}
}
echo '<pre>';
var_dump($newArray);
echo '</pre>';
echo $newArray[0][0];
Obviously I will recommend first way.

Related

PHP: Associate array index name in a foreach loop

I can get the index number from a foreach loop by doing the following.
foreach ($rows as $index=>$row)
{
echo $index.": ".$row;
// gives me "1: $row etc
}
If my array is associative is there away to get the associative name instead of the index number into my loop?
Actually you allready did it:
$associativeArray = array(
'First' => 1,
'Second' => 2,
'Third' => 3,
);
foreach ($associativeArray as $index => $value) {
echo $index . ": " . $value;
}
// First: 1
// Second: 2
// Third: 3
<?
$rows = array();
$rows['hi'] = 'there';
$rows['foo'] = 'bar';
foreach ($rows as $index=>$row)
{
echo $index.": ".$row;
// $index will be hi and foo
}
?>
PHP arrays ARE associative where regular arrays just have integers as keys.
The PHP documentation actually mentions this in the first sentence: http://php.net/manual/en/language.types.array.php
An array in PHP is actually an ordered map..
PHP doesn't have arrays, it has maps/dictionaries that are called arrays but they are not arrays like in other languages.

Combining multiple array values in PHP

I have three arrays right now the values of which I want to combine together. All of the values have matching keys but I can't work out quite how to do it. To put it more visually I have:
array{
[0] => "Foo"
}
array{
[0] => " Bar"
}
and I want:
array{
[0] => "Foo Bar"
}
But for the life of me I can't figure out how! At first I thought about using nested foreach statements like
$result = array();
foreach ($array1 as &$input1) {
foreach ($array2 as &$input2) {
$result[] = $input1 . $input2;
}
}
But while that combined the values, it generated a lot of correct ones (The array was about twice the size as expected).
Use the keys
$output = array();
foreach (array_keys($array1) as $key) {
$output[] = $array1[$key] . $array2[$key]; // and possibly . $array3[$key]
}

Array initialisation with value

Hello guys i have coded something like this ..I just dont know wheather the code is right or not ..But i have a question
THe code is
$featured = array('name' => 12,'yeah' => 10);
foreach($featured as $key => $value){
echo $value['name'];
}
I know that value of name can be acessed by $featured['name']
but now I just need to know wheather the key of array can be acessed with value like $value['name'].
Is it possbile like that ?..
Any help would be appreciated ..Thanks
$featured = array('name' => 12,'yeah' => 10);
foreach($featured as $key => $value){
echo $key; // outputs: name
echo " - ";
echo $value; // outputs: 12
echo "<br />";
}
Yes, it supports that in the next iteration of the loop.
Output:
name - 12
yeah - 10
BTW, one more way of accessing the keys from array.
$featured = array('name' => 12,'yeah' => 10);
while (current($featured)) {
echo key($featured).'<br />';
next($featured);
}
Output:
name
yeah
You most probably want to do:
echo "{$key} => {$value}";
The foreach($featured as $key => $value) statement iterates the array and for each iteration $key and $value contain both the key and value for the tuple.
Take a look at this:
http://php.net/array_search
it searches for the value and returns it's key.
It's not like accessing $array['value'] but it's still userfull if you want to find the key.

Iteration and modification of array best approach

The following is the best way to iterate through and modify array in PHP5.*+
(source: http://zend-php.appspot.com/questions_list -- question #3)
$array = array("one" => 1, "two" => 2, "three" => 3, "four" => 4, "five" => 5);
foreach($array as $key => &$val) {
$val += 1;
}
What is it about this method of iterating and modifying that makes it better than others?
Can someone please explain how come this actually works?
This iterates just fine, why include as $key => &$val if we are not using the keys?, also why do we need to include the & in &$val:
foreach($array as $val){
echo $val;
}
I appreciate the explanation,
Thanks in advance!
Since they intend to modify the value, getting it as a reference is clever.
$array = array("one" => 1, "two" => 2, "three" => 3, "four" => 4, "five" => 5);
foreach($array as $key => &$val) {
$val += 1;
}
Will add 1 to all values.
If you did:
foreach($array as $key => $val) {
$val += 1;
}
Nothing would happen.
I strongly disagree that it is the best way though. I much prefer to see:
foreach($array as $key => $val) {
$array[$key] += 1;
}
because it's much more straightforward. I'll gladly believe it doesn't perform as well, but I also don't care (unless there is a reason to start optimizing).
It's also worth mentioning that using references can lead to strange situations, such as: PHP reference causes data corruption
PS. I didn't downvote. I'm getting really annoyed by people downvoting and not leaving a comment.
The question is as follows:
What is the best way to iterate and modify every element of an array using PHP 5?
These are the four choices listed in the link:
// method one
for($i = 0; $i < count($array); $i++) {
/* ... */
}
// method two
foreach($array as $key => &$val) {
/* ... */
}
// method three
foreach($array as $key => $val) {
/*... */
}
// method four
while(list($key, $val) = each($array)) {
/* ... */
}
The options 1, 3 and 4 are okay and they will work for iterating through the array. However, to modify the original array, you'll need to pass the $val by reference, which is what the second option does. That's why it's the preferred solution, in this case.

Duplicate array values not working with Simple HTML DOM

I'm working with Simple HTML DOM like this:
foreach($html->find('img', 18) as $d) {
echo $d->outertext;
}
Now I want to implement an array of variables, in this case images, so I did:
$img=array(
"img"=>"18",
"img"=>"21"
);
foreach($img as $x=>$x_value)
{
$d = $html->find($x, $x_value);
echo $d->outertext;
}
The problem is that Simple HTML DOM is only returning the last image in array, which is number 21. What do I have to do to make it return everything in the array?
It's because both items in your $img array has the same key. foreach doesn't recognize them as two seperate items because both keys are img.
Example code to demonstrate:
$test = array(
"key" => 1,
"key" => 2
);
echo "Length of array: " . count($test) . "\n\n";
echo "Items in array:\n";
foreach($test as $key => $value) {
echo "$key => $value\n";
}
Outputs:
Length of array: 1
Items in array:
key => 2

Categories