Multi-dimentional Array php condition loop and variable assignment - php

Need some help figuring this out. I have a JSON array going to a php file after the submit is clicked via ajax. Once decoded on the php side, it looks like this:
Array
[0] => Array
(
[ID] => 409
[ChangeType] => CHANGE_SEAT_TO
[Name] => John Doe
[Seat] =>
[setTo] => 4-2
[PreviousSeatValue] =>
[PreviousSeatNewValue] => Y
)
[1] => Array
(
[ID] => 278
[ChangeType] => CHANGE_SEAT_TO
[Name] => John Test
[Seat] => 4-1
[setTo] => 4-3
[PreviousSeatValue] => Y
[PreviousSeatNewValue] => Y
)
[2] => Array
(
[ID] => 305
[ChangeType] => REMOVESEAT
[Name] => John Blue
[Seat] => 3-6
[setTo] => 0
)
[3] => Array
(
[ID] => 314
[ChangeType] => CHANGE_SEAT_TO
[Name] => John Red
[Seat] => 3-4
[setTo] => 3-6
[PreviousSeatValue] => Y
[PreviousSeatNewValue] => Y
)
Main Goal:
What im trying to do is loop through all the arrays and if changetype matches a string("CHANGE_SEAT_TO" or "REMOVESEAT"), execute a SQL statement. Im having issues assigning variables to the different key values in the matching arrays during a loop. Here is what I have so far:
$obj = json_decode($_POST['myData'], TRUE);
foreach ($obj as $innerArray){
foreach($innerArray as $key => $value){
$$key = $value;
if($value === "CHANGE_SEAT_TO"){
echo $ID;
echo $setTo;
}
if($value === "REMOVESEAT"){
echo $ID;
echo $setTo;
}
}
}
Now obviously this is set up for just testing purposes(i have the echo's displaying in the console log after successful ajax). With this setup, I am able to successfully echo out the ID of the matching elements but if I try any other one, the variable is undefined. Can anyone explain why this is happening and offer up a suggestion to the main goal? Thanks in advance.

You need only one foreach(), check the modified code
<?php
$obj = json_decode($_POST['myData'], TRUE);
foreach ($obj as $innerArray){
if($innerArray['ChangeType'] == 'CHANGE_SEAT_TO') {
// do stuff
$id = $innerArray['ID'];
// get rest of values in same way
} else if($innerArray['ChangeType'] == 'REMOVESEAT') {
// do stuff
$id = $innerArray['ID'];
// get rest of values in same way
}
}

Try something like this:
foreach ($obj as $value) {
if ($value['ChangeType'] == 'CHANGE_SEAT_TO') {
echo $value['ID'];
echo $value['setTo'];
} elseif ($value['ChangeType'] == 'REMOVESEAT') {
echo $value['ID'];
echo $value['setTo'];
}
}

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

PHP get array value from json

Using PHP, how would I access the inner array values, specific to this example the values specific to each game array, from a json feed similar to this:
Array
(
[startIndex] => 3
[refreshInterval] => 60
[games] => Array
(
[0] => Array
(
[id] => 2013020004
[gs] => 5
[ts] => WEDNESDAY 10/2
[tsc] => final
[bs] => FINAL
[bsc] => final
)
[1] => Array
(
[id] => 2013020005
[gs] => 5
[ts] => WEDNESDAY 10/2
[tsc] => final
[bs] => FINAL
[bsc] =>
)
I have tried nesting a foreach loop inside a foreach loop similar to this:
foreach ($json as $key => $jsons) {
foreach ($jsons as $my => $value) {
echo $value;
}
}
If that is an array you are looking at then you can reach the values
foreach($json["games"] as $game) {
foreach ($game as $key => $value) {
echo $value;
}
}
This should give you the values within each array in the games section.
EDIT: to answer additional question in comment
To get the specific values of the game like the id, the second foreach loop will not be needed. Instead do the following:
foreach($json["games"] as $game) {
echo $game['id'];
}
You just access it as an associative array.
$json['games'][0]['id'] // This is 2013020004
$json['games'][1]['id'] // This is 2013020005
You can loop through the games like so:
foreach($json['games'] as $game){
print_r($game);
}
If you are trying to access this,
[0] => Array
(
[id] => 2013020004
[gs] => 5
[ts] => WEDNESDAY 10/2
[tsc] => final
[bs] => FINAL
[bsc] => final
)
[1] => Array
(
[id] => 2013020005
[gs] => 5
[ts] => WEDNESDAY 10/2
[tsc] => final
[bs] => FINAL
[bsc] =>
)
..then you are doing it right. The only problem is you are trying to echo an array. Trying using print_r($value). If you want a specific value, like the id. You can echo $value['id'];
I think you could use one of the many example of recursive array_key_search. This way you could simply do :
$firstGame = array_search_key(0, $array);
$firstGameId = $firstGame["id"];

Problems with mutiple array in foreach loops

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

Iterate though a Object and echo values

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

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