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);
Related
I am using CodeIgniter. I am getting twice records on the view page.
$data['upcomingForsecondary']=$this->Access_model->upcomingsecondary($data['getLogininfo']->customer_id);
Getting the output
Array
(
[0] => stdClass Object
(
[member_id] => 337
[first_name] => zxs
[middle_name] =>
[last_name] => asd
[email] => qwe#gmail.com
[dob] => 22-04-1984
[phone] => 1231231231
[landline] =>
[membershipForTheYear] => 2018-2019
)
[1] => stdClass Object
(
[member_id] => 209
[first_name] => sdf
[middle_name] =>
[last_name] => asd
[email] => asdas#gmail.com
[dob] => 24-07-1982
[phone] => 1231231231
[landline] =>
[membershipForTheYear] => 2018-2019
)
)
Now I a passing membershipForTheYear to the model using foreach get the records.
Controller code
$data['upcomingForsecondary']=$this->Access_model->upcomingsecondary($data['getLogininfo']->customer_id);
foreach ($data['upcomingForsecondary'] as $key => $sec_m_id) {
$secClubfees[]=$this->Access_model->getfeesFornewyear($sec_m_id->membershipForTheYear);
}
$data['newFees'] = $secClubfees;
**print_r($data['newFees']) output **
Array
(
[0] => Array
(
[0] => stdClass Object
(
[clubMembershipFees_id] => 1
[clubDuration] => 2019-2020
[clubPrimaryMemberFees] => 100
[startCutoffDate] => 16-02-2019
[endCutoffDate] => 31-03-2019
[is_clubFeesActive] => 1
)
)
[1] => Array
(
[0] => stdClass Object
(
[clubMembershipFees_id] => 1
[clubDuration] => 2019-2020
[clubPrimaryMemberFees] => 100
[startCutoffDate] => 16-02-2019
[endCutoffDate] => 31-03-2019
[is_clubFeesActive] => 1
)
)
)
View code
I tried on view like
foreach ($upcomingForsecondary as $key => $secPersonalInfo) {
/*Displaying personal information which is dislaying perfeclty*/
foreach ($newFees as $key => $value) {
foreach ($value as $key => $rows) {
/*getting issue here. I a getting the twice output*/
}
}
}
view output I am getting like
first member name
fees details
fees details
second member name
fees details
fees details
I used multiple foreach that's the issue. I think there some issue on view page or controller .
Would you help me out in this issue?
Without having an idea, what it's all about - And without a clue of codeigniter :) ..
foreach ($data['upcomingForsecondary'] as $key => $sec_m_id) {
$secClubfees[]=$this->Access_model->getfeesFornewyear($sec_m_id->membershipForTheYear);
}
Here you throw two results together in an array and lose the relations to the objects in $data['upcomingForsecondary'].
Then in the view
foreach ($upcomingForsecondary as $key => $secPersonalInfo) {
// Displaying personal information
foreach ($newFees as $key => $value) {
// show the rows
}
}
you loop the two results in newFees twice (once per object in $upcomingForsecondary).
So you need to relate the inner loop with the outer loop using either $key or $secPersonalInfo. I can suggest three ways to do that.
#1 Hope that the keys are the same:
foreach ($upcomingForsecondary as $key1 => $secPersonalInfo) {
// Displaying personal information
foreach ($newFees[$key1] as $key2 => $rows) {
// show the row
}
}
#2 Make sure the keys are the same:
foreach ($data['upcomingForsecondary'] as $key => $sec_m_id) {
$secClubfees[$key] = $this->Access_model->getfeesFornewyear($sec_m_id->membershipForTheYear);
}
Then use the view code from #1
#3 Nest the results:
Controller:
foreach ($data['upcomingForsecondary'] as $key => $sec_m_id) {
$sec_m_id->newFees
= $this->Access_model->getfeesFornewyear($sec_m_id->membershipForTheYear);
}
You don't need $data['newFees'] in this case.
View:
foreach ($upcomingForsecondary as $key1 => $secPersonalInfo) {
// Displaying personal information
foreach ($secPersonalInfo->newFees as $key2 => $rows) {
// show the row
}
}
Personally I prefer #3
I am needing to echo out the [number], but as you can see each array has a different parent [], how do I by pass the first one and get go to the [number]?
I basically need to skip over first [], and go to the second on that is [number]
Array
(
[e2a4789d22ff47779722b8d8643894cd] => Array
(
[type] => workphone
[visibility] => public
[number] => 999-999-9999
[id] => 2
[order] => 0
[preferred] => 1
)
)
Array
(
[1603ebeff250437480f5ce046cac36aa] => Array
(
[type] => workphone
[visibility] => public
[number] => 999-999-9999
[id] => 3
[order] => 0
[preferred] => 1
)
)
Array
(
[215590630122] => Array
(
[type] => workphone
[visibility] => public
[number] => 999-999-9999
[order] => 0
[preferred] =>
)
)
Your solution for this is using the foreach-loop. Which gives you then the value of the element as variable you tell PHP to assign to.
foreach($array as $element) {
}
You have to use reset function to get the first element of array.
e.g.
$firstElement = reset($arr);
echo $firstElement['number'];
You can just loop over the elements in the array(s) using foreach.
foreach($data as $ele){
foreach($ele as $id=>$val){
echo $val['number'];
}
}
Just an example
$array = $yourarray;
foreach($array as $k=>$v) {
echo $v['number'] . '<br>';
}
hope this helps...
The first bracket is just a unique key index foreach subsequent set of data. for example you can get the first set by accessing through the key like this
$data['e2a4789d22ff47779722b8d8643894cd']
// will return
Array
(
[type] => workphone
[visibility] => public
[number] => 999-999-9999
[id] => 2
[order] => 0
[preferred] => 1
)
loop through the array to access the data you want,
// declare your array if you want to save data in array
$numbers = [];
foreach($data $key =>$value){
// echo just the number
echo $value['number'];
// echo the key and number
echo $key.' '.$value;
// or you can build an array
$numbers[$key] = $value['number'];
}
print_r($numbers);
Hope you find this useful, for more info about arrays take a look at this http://php.net/manual/en/language.types.array.php
foreach ($array as $id => $element)
{
// will echo 999-999-9999
echo $element['number'];
}
$array is the whole data structure. We go through as index, that is the $id, which is for example e2a4789d22ff47779722b8d8643894cd and the $element is the element in the $array[$id] so in the $array[e2a4789d22ff47779722b8d8643894cd]
So the $element is the small array in the large array, and it contains data like:
Array
(
[type] => workphone
[visibility] => public
[number] => 999-999-9999
[id] => 2
[order] => 0
[preferred] => 1
)
So if you need the number attribute, you type $element['number'] and you get it.
If your variable was in an array called $elements then it would look like:
$elements['e2a4789d22ff47779722b8d8643894cd']['number']
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've "inherited" some data, which I'm trying to clean up. The array is from a database which, apparently, had no keys.
The array itself, is pretty long, so I'm simplifying things for this post...
[0] => Array
(
[id] => 2
[uid] => 130
[eid] => 8
[ename] => Standard
[eaction] => Check
)
[1] => Array
(
[id] => 2
[uid] => 110
[eid] => 8
[ename] => Standard
[eaction] => Check
)
[2] => Array
(
[id] => 2
[uid] => 200
[eid] => 8
[ename] => Standard
[eaction] => Check
)
I'm trying to shift things around so the array is multidimensional and is grouped by ename:
[0] => Array
(
[Standard] => Array
(
[id] => 2
[uid] => 130
[eid] => 8
[eaction] => Check
)
)
[0] => Array
(
[Standard] => Array
(
[id] => 2
[uid] => 130
[eid] => 8
[eaction] => Check
)
)
[0] => Array
(
[Standard] => Array
(
[id] => 2
[uid] => 130
[eid] => 8
[eaction] => Check
)
)
Anyone know how to do something like this?
You can use usort() to sort an array by a user-defined function. That function could compare the ename fields. Then it's just a simple transformation. Like:
usort($array, 'cmp_ename');
function cmp_ename($a, $b) {
return strcmp($a['ename'], $b['ename']);
}
and then:
$output = array();
foreach ($array as $v) {
$ename = $v['ename'];
unset($v['ename']);
$output[] = array($ename => $v);
}
$outputarray = array();
foreach($inputarray as $value) {
$outputarray[] = array($value['ename'] => $value);
}
would accomplish what your examples seem to indicate (aside from the fact that your 'result' example has multiple things all with key 0... which isn't valid. I'm assuming you meant to number them 0,1,2 et cetera). However, I have to wonder what benefit you're getting from this, since all it appears to be doing is adding another dimension that serves no purpose. Perhaps you could clarify your example if there are other things to take into account?
$outputarray = array();
foreach($inputarray as &$value) {
$outputarray[][$value['ename']] = $value;
unset($value['ename']);
} unset($value);
I'm guessing that this is what you're asking for:
function array_group_by($input, $field) {
$out = array();
foreach ($input as $row) {
if (!isset($out[$row[$field]])) {
$out[$row[$field]] = array();
}
$out[$row[$field]][] = $row;
}
return $out;
}
And usage:
var_dump(array_group_by($input, 'ename'));
philfreo was right but he was also off a little. with his code every time you encounter an array element with an ['ename'] the same as one you've already gone through it will overwrite the data from the previous element with the same ['ename']
you might want to do something like this:
$output = array();
foreach ($YOURARRAY as $value) {
$output[$value['ename']][] = $value;
}
var_dump($output); // to check out what you get