Problems with mutiple array in foreach loops - php

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

Related

Records are getting twice on the view page

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

How do I get the array values from two arrays by using keys

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..

Change value of multidimensional php array with function result

I have the feeling I am missing something simple. I need to change the value of a key in a multi dimensional array based on the result of a function. Here is my array $exports
Array (
[0] => Array (
[captain] => Yes
[uniform] => 3
[fname] => Sally
[lname] => Smith
[position1] => OH
[position2] =>
[position3] =>
[bio] =>
[classyear] => 2015
[hft] => 5
[hin] => 7
)
[1] => Array (
[captain] => Yes
[uniform] => 2
[fname] => Danielle
[lname] => Smith
[position1] => L
[position2] => S
[position3] => OH
[bio] =>
[classyear] => 2016
[hft] => 5
[hin] => 2
)
[2] => Array (
[captain] => No
[uniform] => 4
[fname] => Erica
[lname] => Smith
[position1] => RS
[position2] =>
[position3] =>
[bio] =>
[classyear] => 2018
[hft] => 5
[hin] => 9
)
)
This is the code I am using.
foreach($exports as $key => &$value)
{
foreach($value as $key1 => &$value1)
{
if( $key1 == "classyear") $value1=JHtml::_('helper.gradenumber', $value1, $season);
}
unset($value1);
}
unset($value);
return $exports;
This is within Joomla so the JHml line is my function. If I replace this with a string, then my array is updated correctly, but using the function, my classyear key is empty. I have tested and know the function is returning the correct value.
It seems like what you have should mostly work, but in this part:
$value1=JHtml::_('helper.gradenumber', $value1['classyear'], $season)
I think $value1['classyear'] should just be $value1,
because if( $key1 == "classyear") then $value1 will just be a number.
Also, if you are seeing all the results of the classyear function first, you may have it echoing the value instead of returning it.
You could probably use array_walk for this.
array_walk($exports, function (&$value) use ($season) {
$value['classyear'] = JHtml::_(
'helper.gradenumber', $value['classyear'], $season);
});
You referenced to your $value and $value1, and then unset them. Do not use references, instead of that, update the value like this:
foreach ($exports as $key => $value) {
foreach ($value as $key1 => $value1) {
if ($key1 == "classyear") {
$exports[$key1] = JHtml::_('helper.gradenumber', $export['classyear'], $season);
}
}
}
Can use array_key_exists() to check key exist or not. No need to use nested foreach() . Example:
$finalArray = array();
foreach($exports as $key => $value)
{
if(array_key_exists("classyear", $value)){
$value["classyear"] = JHtml::_('helper.gradenumber', $export['classyear'], $season);
}
$finalArray[] = $value;
}
I haven't tested this code, but array_walk_recursive() seems to me to be the way to handle this:
function changeKey(&$item, $key) {
if($key == 'classyear') {
$classYear = $item;
$item = JHtml::_('helper.gradenumber', $classYear, $season);
}
}
array_walk_recursive($exports, 'changeKey');

Output two-dimensional array

Ok, I'm still struggling with my arrays... I have created a two-dimensional array and saved into a session to get results on another page: $_SESSION['myARRAY']
print_r($_SESSION['myARRAY']);
// will output:
Array ( [Car] => Array ( [0] => 1 [1] => 9 [2] => 0 )
[Truck] => Array ( [0] => 2 [1] => 10 [2] => 0 )
[Bus] => Array ( [0] => 1 [1] => 8 [2] => 2 ))
Now I need to output the data into the following format:
$xls->addRow(Array("Car",1,9,0));
$xls->addRow(Array("Truck",2,10,0));
$xls->addRow(Array("Bus",1,8,2));
I tried to do something like this:
foreach($_SESSION['myARRAY'] AS $key => $value) {
$arr[$key] = $key;
foreach($value AS $k => $v) {
$arr[$key] = $v;
}
$xls->addRow($arr[$key]);
}
but it did not really work. I think I'm close but not quite there...
$value is already an array. Now you only need to prepend the $key to it. You could use array_unshift:
foreach($_SESSION['myARRAY'] AS $key => $value) {
array_unshift($value, $key);
$xls->addRow($value);
}
Of course if you do this more than once, you should consider storing the consolidated array.
I'd probably use array_unshift as it seems like a more appropriate way to solve this problem, but you could also do it like:
foreach($_SESSION['myARRAY'] AS $key => $value) {
$xls->addRow(array_merge(array($key), $value));
}

PHP invalid argument supplied in foreach

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);

Categories