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
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 apologize if this is a very simple question - I've read through tons of posts here, but my question is syntactically very hard to search for, so I haven't found an answer yet.
I have a json array that's output from a company's API:
[Result] => Array
(
[cData] => Array
(
[0] => Array
(
[Reqa] => ABCD
[Reqb] =>
[Reqc] => Plus
[dto] => Array
(
[0] => Array
(
[ComID] => 43292392
[Comment] => Dave
)
[1] => Array
(
[ComID] => 43292392
[Comment] => Bob
)
)
[XREFSearchOperation] => Exact
)
[1] => Array
(
[Reqa] => BCDE
[Reqb] =>
[Reqc] => A
[dto] => Array
(
[0] => Array
(
[ComID] => 19331186
[Comment] => Mike
)
[1] => Array
(
[ComID] => 19331186
[Comment] => Roger
)
)
[XREFSearchOperation] => Starts With
)
[2] => Array
(
[Reqa] => QQDT
[Reqb] =>
)
)
)
)
and I'm trying to access the [ComID] and [Comment] elements, if they exist, inside of a foreach loop and assign it to the variable $y
So far I have:
foreach ($json['Result']['cData']['dto'] as $i) {
$y = "{$i['ComID']}|{$i['Comment']}";
}
but this gives me zero results. I understand WHY, because in between ['cData'] and ['dto'] are [0], [1], [2] etc.. elements, and I don't know how to add a qualifier for those into the loop.
Update
This code works for most of the json response:
foreach ($json['Result']['cData'] as $i) {
if(array_key_exists('dto', $i)) {
foreach ($i['dto'] as $j) {
$y = "{$j['ComID']}|{$j['Comment']}";
} else {
}
}
However - I'm having one more small issue. If there are multiple [dto] responses, you'll have [dto][0][ComID] then [dto][1][ComID] and [dto][2][ComID], (like in the example above,) but if there's only ONE response, you'll have [dto][ComID] as there's no need for that middle array.
I tried writing if(array_key_exists('dto[0]' to execute one, then an else statement in the event dto[0] doesn't exist, but that didn't work. I need a way of NOT executing a foreach loop if there is no array underneath it to "foreachicize". Is there an if/else statement I can write to accommodate this?
Probably need a nested foreach:
foreach ($json['Result']['cData'] as $i) {
foreach($i['dto'] as $j) {
$y[] = "{$j['ComID']}|{$j['Comment']}"; //need an array here
}
}
For the update to the question. Check if $i['dto'][0] exists:
foreach ($json['Result']['cData'] as $i) {
if(isset($i['dto'][0]))) {
foreach($i['dto'] as $j) {
$y[] = "{$j['ComID']}|{$j['Comment']}";
}
} else {
$y[] = "{$j['ComID']}|{$j['Comment']}";
}
}
There might be a better way but I'm headed out.
Another approach:
foreach($json['Result']['cData'] as $cData)
{
foreach($cData['dto'] as $dto)
{
if(array_key_exists('ComID', $dto) && array_key_exists('Comment', $dto))
{
$y = "{$dto['ComID']}|{$dto['Comment']}";
}
}
}
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 have an array which is the result of a select query using Amazon SimpleDb.
Here is sample data when I print_r($result);
Array ( [0] => Array ( [Name] => 5140ede647e74
[Attributes] => Array (
[0] => Array ( [Name] => test_id [Value] => 5140ede647e74 )
[1] => Array ( [Name] => test_name [Value] => test1 )
[2] => Array ( [Name] => last_update [Value] => 1363209702 )
[3] => Array ( [Name] => created [Value] => 1363209702 ) ) ) )
If I want to extract the test_id and the test_name, how can I do it? I am currently doing the following
<?php foreach ($result as $item) {
echo $item['Attributes'][0]['Value'];
echo $item['Attributes'][1]['Value'];
} ?>
But I want to do it by referencing "test_id" and "test_name" because when I delete the domain where the data resides and re-enter the data, the order of each attribute can change so I can't trust that $item['Attributes'][0]['Value'] will always be the test_id
Thanks!
foreach ($result as $item) {
foreach ($item['Attributes'] as $keyvalue) {
if ($keyvalue['Name'] == 'test_id' || $keyvalue['Name'] == 'test_name') {
echo $keyvalue['Value'];
}
}
}
You need to recast the Array.
$newArray = array();
foreach ($result as $key=>$row)
{
foreach ($row['Attributes'] AS $row2)
{
$newArray[$key][$row2['Name']] = $row2['Value'];
}
}
EDIT: It depends on what you need to do - this is my preferred method if I plan on doing a lot of work with a resultset - I only need to iterate through the set once and then it's in a format where the data can be accessed quickly.
The following will run trough the last part of your array by reference. Therefore edits that you make are reflected in the $result array.
foreach ($result[0]['Attributes'] as &$item) {
if ($item['Name'] == 'test_id') // do something
}
I have the following function executing PDO queries:
// removed error handling for presenting here
function getRows($sql) {
$stmt = $this->db->query($sql);
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
return $result;
}
}
The result is:
Array
(
[0] => Array
(
[id] => 1
[category] => Audi
)
[1] => Array
(
[id] => 2
[category] => BMW
)
[2] => Array
(
[id] => 3
[category] => Chrysler
)
)
The the following foreach code:
foreach($result as $key => $value ) {
echo $value.'<br/>';
}
outputs this:
Array
Array
Array
What can I do so it returns the following?
Audi
BMW
Chrysler
I understand that I could just do $value['category].
But that's not what I want to achieve / understand. I would like the resultset not to be an array of arrays.
try
foreach($result as $key => $value ) {
echo $value['category'].'<br/>';
}
Alternative
foreach($result as $k)
{
echo $k['category'];
}
The foreach loop splits up your array into key, value pairs. The key in your loop is the index of the array, the value is an array containing ID and Category.
To access the category simply do:
foreach($result as $key => $value ) {
echo $value['category'].'<br/>';
}