I am trying to get the item id, and then all option_name/option_values within that item id. So I end up with, ID: 123, Color: Blue, Size: 6. ID: 456, Color: Yellow, Size: 8. However I am getting the correct item ID, but the option_name/option_value isn't coming through correctly, either blank or just one random letter.
Here's my code that doesn't work,
foreach($itemlist as $item)
{
echo $item['ID'];
foreach($item as $option)
{
echo $option['option_name'];
echo $option['option_value'];
}
}
Where $itemlist looks like this:
Array
(
[1] => Array
(
[ID] => 123
[QTY] => 1
[MODEL] => sdfsd
[IMAGE] =>
[1] => Array
(
[option_name] => Color
[option_value] => Blue
[option_price] => 0.0000
)
[2] => Array
(
[option_name] => Size
[option_value] => 6
[option_price] => 0.0000
)
[price] => 0
)
[2] => Array
(
[ID] => 456
[QTY] => 0
[MODEL] => gsdfgd
[IMAGE] =>
[1] => Array
(
[option_name] => Color
[option_value] => Yellow
[option_price] => 0.0000
)
[2] => Array
(
[option_name] => Size
[option_value] => 8
[option_price] => 0.0000
)
[price] => 0
)
)
Basically, you're looping over the $item array, which looks like this:
array(7) {
["ID"]=>string(6) "123"
["QTY"]=>string(1) "1"
["MODEL"]=>string(11) "sdfsd"
["IMAGE"]=>string(0) ""
[1]=>
array(3) {
["option_name"]=>string(8) "Color"
["option_value"]=>string(10) "Blue"
["option_price"]=>string(6) "0.0000"
}
So on the first iteration, $option will be 123, trying to access '123'['option_name'] will issue a warning. What you actually wanted to do is this:
foreach($item[1] as $key => $option)
{
if ($key !== 'option_price')
{
echo $option;
}
}
//or:
echo $item['ID'], $item[1]['option_name'], $item['option_value'];
That's why your code doesn't produce the desired result.
If the sub-array doesn't always have 1 as a key, try:
foreach($item as $foo)
{
if (is_array($foo))
{
echo $foo['option_name'], $foo['option_value'];
break;//we have what we needed, no need to continue looping.
}
}
Here's the most generic approach to get all options (irrespective of how many)
foreach($itemlist as $item)
{
echo $item['ID'];
foreach($item as $sub)
{
if (is_array($sub))
{
foreach($sub as $key => $option)
{
echo $key, ' => ', $option;
}
}
}
}
But seeing as your options arrays look like they all have numeric indexes, you could just as well try this:
foreach($itemlist as $item)
{
echo $item['ID'];
for ($i=1;isset($item[$i]);$i++)
{
foreach($item[$i] as $key => $option)
{
echo $key, ' => ', $option;
}
}
}
You could replace the for loop with:
$i=0;//or $i = 1
while(isset($item[++$i]))// or isset($item[$i++]), if $i is 1
This is because your array contains the POSSIBILITY of those keys existing, not guaranteed. There's a few different approaches you could take, such as checking if the key is numeric (seems only numeric keys have the correct array of keys set). But since i dont know your dataset, probably the best universal method is to change your code to check if the key's are set, before trying to use them. So..
foreach($itemlist as $item) {
foreach($item as $key => $value) {
if(is_array($value) && array_key_exists('option_name', $value) {
//--- Your option array is available in here via $value['option_x']
}
}
}
You could try something like:
array_walk_recursive($itemlist, function($value, $key) {
if (in_array($key, array("ID", "option_name", "option_value")))
echo "$key: $value\n";
});
Related
My arrays are
$name=>
Array
(
[0] => General
[1] => General
[2] => Outdoors
[3] => Dining
[4] => Dining
[5] => Kitchen
[6] => Kitchen
)
$key1=>
Array
(
[0] => 1
[1] => 2
[2] => 7
[3] => 11
[4] => 12
[5] => 17
[6] => 18
)
Array function
foreach ($key1 as $key => $value1) {
foreach ($name as $key => $value) {
echo $value "=>" $value1 ;
//echo "$value1";
}
}
Here I would like to print the values by using the same keys
if $name having the index as [0] and my $key1 also take the [0] value
i.e: my result should be in the form of
General => 1
General => 2
Outdoors => 7
Dining => 11
Dining => 12
Kitchen => 17
Kitchen => 18
You only need to iterate one array, not both of them:
foreach ($name as $key => $name_value) {
echo "$name_value => " . $key1[$key];
}
You can use a simple for loop to do this
for ($i = 0; $i < count($name); $i++) {
echo $name[$i] . '=>' . $key[$i]
}
The problem with your code is you're using the same variable $key for both foreachs, so the last one overwrites the value.
foreach ($key1 as $key => $value1) {
foreach ($name as $key => $value) {
echo $value "=>" $value1 ;
//echo "$value1";
}
}
You could make things easier by combining those two arrays, making $name array be the keys and $key1 array be the values
$newArray = array_combine($name, $key1);
foreach ($newArray as $name => $key) {
echo "{$name} =>{$key}";
}
This will work for you
<?php
$a1= array('General','Outdoors','Dining ');
$a2= array('1','2','3');
$newArr=array();
foreach($a1 as $key=> $val)
{
$newArr[$a2[$key]]= $val;
}
echo "<pre>"; print_r($newArr);
?>
output
Array
(
[1] => General
[2] => Outdoors
[3] => Dining
)
I am afraid this wont be possible if you want the output as associative array as same key name in an associative array is not allowed. It would be always overwritten if you are dealing with the associative arrays.
Although you may have something like this:
array_map(function($key, $val) {return array($key=>$val);}, $name, $key1)
Output:
Array ( [0] => Array ( [General] => 1 ) [1] => Array ( [General] => 2 ) [2] => Array ( [Outdoors] => 7 ) [3] => Array ( [Dining] => 11 ) [4] => Array ( [Dining] => 12 ) [5] => Array ( [Kitchen] => 17 ) [6] => Array ( [Kitchen] => 18 ) ).
But if you want the output in string format It is possible.
for ($i = 0; $i < count($key); $i++) {
echo $name[$i] . '=>' . $key[$i].'<br>';
}
Just change the foreach as follows...
foreach ($key1 as $key => $value1) {
echo $name[$key] ."=>". $value1."<br>";
}
replace the <br> with \n if you're running through the linux terminal. Also don't miss the '.' operator to concatenate the string..
Nested foreach won't do what you need... Good luck..
This is my first question here so i dont exactly know the normal style.
I have a problem with multiple arrays. My arrays are sorted this way:
Array
(
[count] => 2
[gebruikerData] => Array
(
[gebruiker1] => Array
(
[merken] => Array
(
[0] => merk1
[1] => merk10
[2] => merk19
)
[loginnaam] => testfasdfasd
[geslacht] => Man
[persoonlijkheidsType] => TEST
[beschrijving] => fasdfasdfasd
[gebruikerID] => 19
[leeftijd] => 21
)
[gebruiker2] => Array
(
[merken] => Array
(
[0] => merk1
[1] => merk9
[2] => merk36
)
[loginnaam] => test1233
[geslacht] => Man
[persoonlijkheidsType] => TEST
[beschrijving] => safasfd
[gebruikerID] => 20
[leeftijd] => 21
)
)
)
I need to retrieve all the information in this array. There can be as many fields gebruiker(number) as the database output, so i tried to use multiple foreach loops in eachother. My problem is that it is not possible to use the key from one foreach loop as index in another foreach loop like this:
foreach ($gebruikerData as $key => $value)
{
foreach ($key as $key2 => $value2)
{
echo $key2;
}
}
Does anyone have another idea how i could retrieve the information from the array? Or is if could use my own way with a slight change?
Try like this
foreach ($gebruikerData as $key => $value)
{
if(is_array($key))
{
foreach ($key as $key2 => $value2)
{
if(is_array($key2))
{
foreach($key2 as $key3=>$value3)
echo $key3.'-'.$value3;
}
else
echo $key2.'-'.$value2;
}
}
else
echo $key.'-'.$value;
}
Check for the $key is "array or not" each time,if it is array then it will fo to for loop orelse it will echo it directly
I tried a lot of different methods. I managed to get the first part working but the second part to get the fruits name isn't working.
I have an object stored in $food, the print_r() output of this object is shown below:
Food Object
(
[id] => 1
[values] => Array
(
[name] => Myfood
)
[objects] => Array
(
[0] => Fruits Object
(
[id] => 1
[values] => Array
(
[name] => My Fruits
)
[objects] => Array
(
[0] => FruitType Object
(
[id] => 1
[values] => Array
(
[name] => Orange1
)
)
)
)
)
)
This code displays 'Myfood' successfully:
foreach ($food->values as $key => $value) {
echo "$key => $value";
}
This code displays 'My fruits' successfully:
echo '<br/>';
foreach ($food->objects as $id => $owner) {
foreach ($owner->values as $key => $value) {
echo "$key => $value";
}
}
I need a second block of code that displays the FruitType object values Orange1, I tried a few things but didn't work out well.
It looks as if you've run into the greatest stumbling block all developers face... naming things. I've probably not done too much better as I'm not 100% sure what your end goal is but you were on the right track as far as nesting loops is concerned.
foreach ($food->objects as $i => $obj) {
echo "name => {$obj->values['name']}\n";
foreach ($obj->objects as $j => $type) {
foreach($type->values as $key => $val){
echo " $key => $val\n";
}
}
}
Working Example
Looking at the structure of your object though - recursive iteration may be more readable.
Why don't you just use the get_object_vars() function ?
see more here : http://php.net/manual/fr/function.get-object-vars.php
I need to print the below array structure as:
Node Title 1
topic 1
topic 2
topic 3
topic 4
asset title1
asset title2
asset title3
How can i do using foreach - PHP
What i have done is :
foreach($output['fields'] as $key => $value) {
if($key == 'title') {
echo $value;
}
if(count($value['main_topic'])) {
foreach($value['main_topic'] AS $mainkey => $main_topic) {
echo $main_topic['topic_title'];
}
}
}
The above syntax is printing the title. But not the main_topic array.
Array
(
[fields] => Array
(
[nid] => 136
[node_title] => Node title 1
[node_type] => curriculum
[title] => Node title 1
[main_topic] => Array
(
[0] => Array
(
[row_id] => 136
[topic_id] => 411847
[weight] => 10
[topic_title] => topic 1
)
[1] => Array
(
[row_id] => 136
[topic_id] => 411839
[weight] => 2
[topic_title] => topic 2
)
[2] => Array
(
[row_id] => 136
[topic_id] => 411840
[weight] => 3
[topic_title] => topic 3
)
[3] => Array
(
[row_id] => 136
[topic_id] => 411841
[weight] => 4
[topic_title] => topic 4
[subfield] => Array
(
[1] => Array
(
[asset_title] => asset title 1
)
[2] => Array
(
[asset_title] => asset title 2
)
[3] => Array
(
[asset_title] => asset title 3
)
)
)
)
)
)
That is because you are iterating over all $output['fields'].
There will never be a $value with key 'main_topic' because the key 'main_topic' is contained in the $output['fields'] array and thus exists only as $key in your foreach. The array you want is $value
Your code should be like:
foreach($output['fields'] as $key => $value) {
if($key == 'title') {
echo $value;
continue;
}
if($key == 'main_topic' && is_array($value)) {
foreach($value as $main_topic) {
echo $main_topic['topic_title'];
}
}
}
To complete this answer with a full solution (including asset titles), below is how I would write it.
Because $output['fields'] is the starting point and to make the code more readable, I create a reference to the starting node using the =& operator so the array is not copied in memory. I do the same with the inner foreachs. Since we are not modifying data, referencing the variables is sufficient and consumes less memory and CPU:
if (is_array($output['fields'])) {
$node =& $output['fields'];
echo $node['title'];
if(is_array($node['main_topic'])) {
foreach($node['main_topic'] as &$main) {
echo $main['topic_title'];
if(is_array($main['subfield'])) {
foreach($main['subfield'] as &$asset) {
echo $asset['asset_title'];
}
}
}
}
}
else {
echo "no menu";
}
$value is the array, not $key['main_topic']
foreach($output['fields'] as $key => $value) {
if($key == 'title') {
echo $value;
}
if($key == 'main_topic') {
foreach($value as $mainkey => $main_topic) {
echo $main_topic['topic_title'];
}
}
}
Try this, you need the additional key:
echo $value['main_topic'][$mainkey]['topic_title'];
You're getting your array sections confused.
Try (and I haven't tested this) :
echo $output['node_title']."\n";
foreach ($output['fields'] as $key=>$value)
{
switch ($key)
{
case 'title':
echo $value."\n";
break;
case 'main_topic':
if (count($value) > 0)
{
foreach ($value as $main_block)
{
echo "\t".$main_block['topic_title']."\n";
if (array_key_exists('subfield',$main_block)!==FALSE)
{
foreach ($main_block['subfield'] as $subfield_block)
{
echo "\t\t".$subfield_block['asset_title']."\n";
}
}
}
}
break;
default:
break;
}
}
I am trying to read out this nested array with a foreach loop but get an error "invalid argument supplied in foreach"
Array (
[regenerated] => 1302668837
[id] => 2
[qty] => 1
[price] => 1200
[name] => support
[optione] =>
[cart_contents] => Array (
[c4ca4238a0b923820dcc509a6f75849b] => Array (
[rowid] => c4ca4238a0b923820dcc509a6f75849b
[id] => 1
[qty] => 1
[price] => 29.95
[name] => Training DVD
[optione] =>
[subtotal] => 29.95
)
[c81e728d9d4c2f636f067f89cc14862c] => Array (
[rowid] => c81e728d9d4c2f636f067f89cc14862c
[id] => 2
[qty] => 1
[price] => 1200
[name] => support
[optione] =>
[subtotal] => 1200
)
[total_items] => 2
[cart_total] => 1229.95
)
[johndoe] => audio
[totalItems] => 2
)
$cart_contentz = $_SESSION['cart_contents'];
foreach($cart_contentz as $itemz => $valuez) {
foreach($valuez as $key1 => $value1) {
echo "$key1: $value1<br>";
}
the first level of your main array has items that are sub-arrays and some that are not. Your second loop doesn't work on non-array items.
Thus, your code should be:
foreach($cart_contentz as $itemz => $valuez) {
if (is_array($valuez)) {
foreach($valuez as $key1 => $value1) {
echo "$key1: $value1<br>";
}
} else {
echo "$itemz: $valuez<br>";
}
}
you'll need to load that array into your $_SESSOIN['cart_contents'] which may have been done. secondly, your inner foreach is acting on the values of that array which are not arrays. I'm fairly certain that the inner foreach is causing your woes. Also, your Array may just be for illustrating what's in $_SESSION['cart_contents'], but adding quotation marks instead of square brackets around the keys will make it more uniform and easier to read.
Update:
after seeing the reformatted code, thanks #AgentConundrum, now I can more clearly see the issue. Try adding an if(is_array($valuez)) around your inner foreach.
Maybe to use recursion:
function printArray($array, $parent=false, $level=0) {
if (!($parent === false)) echo "<b>".str_pad('',($level-1)*4,"-")."[$parent] =></b><br />\n";
foreach ($array as $key=>$value) {
if (!is_array($value)) echo str_pad('',$level*4,"-")."[$key] => $value<br />\n";
else printArray($value, $key, $level+1);
}
}
print_array($your_array);