How to get array values without forloop? - php

I have a json_decode array which I can access the values fine with a foreach like this :
foreach ($prodvariants["result"]["sync_variants"] as $variant) {
echo $product_name = $variant['product']['name'];
}
This works great.
But what if I do not want a foreach? How can I access the same values but without the forloop?
I tried this
$variant =$prodvariants["result"]["sync_variants"];
echo $product_name = $variant['product']['name'];
But when I try it like this,without the foreach I get error
Notice: Undefined index: product

You missed one key there.
echo $product_name = $variant[0]['product']['name'];
^^^
If JSON has numeric keys, it will be [0]. If you're using another keys, just change it.
But without any loop (for, foreach, while) you can't access to all variants in one line of code. You can choose just a single record. It's a non-sense to get loop out.

Related

Notice: Trying to get property of non-object With Array of objects

I had got this notice, when I try to foreach all my objects in Array:
Notice: Trying to get property of non-object With Array of objects
What can I do to get all row of my Array to put them into a table?
foreach ($this->CollectionArray[$IdVisitor] as $row) {
echo'<tr>';
echo'<td>'.$row->number.'</td>';
echo'<td>'.$this->CollectionArray[$IdVisitor]->date.'</td>';
I got error in echo'<td>'.$row->number.'</td>';
ÉDIT: When I use only collectionArray without foreach it works, but only the last row is showed . It’s why I use foreach to get all rows
Try to use it like this:
foreach ($this->CollectionArray as $row) {
echo'<tr>';
echo'<td>'.$row->number.'</td>';
echo'<td>'.$row->date.'</td>';
}
It will iterate over $this->CollectionArray, so you don't have to specify the index.

Issues creating an associative array with another array in PHP

I'm trying to create an associative array in PHP using an Object. The Object is values from a database, called Category. It only has two values, an id and a name field.
This is what I have:
$category = $em->getRepository('AppBundle:Category')->findAll();
$stuff = array();
foreach($category as $cat) {
$stuff[$cat->getName()] = $stuff[$cat->getId()];
}
But I get this nasty error:
Notice: Undefined offset: 1
I should say that I am using Symfony 3. Any help would be great.
You're on the right track but you need to remove echo since you're not trying to output anything. You're also attempting to assign a value from the array you're trying to enter a value into.
$stuff[ $cat->getName() ] = $cat->getId();
Sorry I just omitted the value and replace with $cat->getId() in stead of $stuff[$cat->getId()] and it worked
You $stuff array has no index 1, so it will cause that issue.
This is caused by $stuff[$cat->getId()];, which should be $cat->getId();
foreach($category as $cat) {
$stuff[$cat->getName()] = $cat->getId();
}

array isn't combining with loop in php

i've a array problem couldn't just solve it:
here's the code that is already in a foreach loop. i'm getting the $row->class_id value from this loop. it works fine and get me the total students row within an array and i preserved it in $total_student_of_this_class variable. i used another foreach loop for storing the result of first loop and then second loop and so on. but this loop gives only first loop result.
i need to combine the all array of total iteration of the loop.
$total_student_of_this_class =
$this->db->select('student_id')->where('class_id',
$row->class_id)->get('student')->result_array();
echo count($total_student_of_this_class);
// prints 2 in the first row of the output table and 5 in the second
row for me.
$total_student = array();
foreach ($total_student_of_this_class as $tt)
{
$total_student[] = $tt;
}
echo '<pre>';
print_r($total_student_of_this_class);
echo '</pre>'
echo count($total_student);
// prints only 2 outside the loop (not 7)
pls someone help me.
The problem here is seems to be with $total_student = array();: initializing array inside an other loop it always starts it from zero values array, so you get only results from one iteration inside it and doesn't collect all datas.
You can also look at array_merge php function.

echo parts of json returned in php

my returned json looks like this http://pastebin.com/Nbr161s3
I want to echo
body->airTicketListResponse->routings->mainAirlineName
body->airTicketListResponse->routings->adultBasePrice
body->airTicketListResponse->routings->trips->segments->departureAirportCode
body->airTicketListResponse->routings->trips->segments->departureTime //only the time here
body->airTicketListResponse->routings->trips->segments->duration
for each routings.
How do I do this? Here is what I have but I am lost and I know it is way off.
$result = data returned here http://pastebin.com/Nbr161s3
$airTicketListResponse = $result->body->airTicketListResponse;
$routings = $result->body->airTicketListResponse->routings;
$trips = $result->body->airTicketListResponse->routings->trips;
$segments = $result->body->airTicketListResponse->routings->trips->segments;
foreach($airTicketListResponse as $item){
$i=0;
$i<count($routings);
echo '<span style="font-weight:bold;">Airline - '.$item->routings[i]->mainAirlineName.' Price - '.$item->routings[i]->adultBasePrice.'</span><br />'.$item->routings[i]->trips[i]->segments[i]->departureAirportCode.' '.$item->routings[i]->trips[i]->segments[i]->departureTime.'<br /><br />';
$i++;
}
Please help if you can.
Before working with JSON you should be familiar with working with arrays and objects since JSON is nothing more than that.
It seems you already know these two concepts
To access an object property in PHP you use obj->property
To access a value of an array you specify the index inside brackets array[0]
With JSON you just have to keep in mind that some of your object properties will be arrays.
Now, since your data comes in a multi-level three-like structure you should also be familiar with traversing arrays, PHP offers an implementation of a foreach loop that is ideal for traversing dynamically generated arrays
using foreach($array as $index => $var) the $index and $var variables are automatically set to the index and value of each element in the array as they are being traversed, so you don't manually need to keep track of the index (i.e. $i)
Now let's start going through your data:
First we find your routings array
$result = json_decode($data);
$airTicketListResponse = $result->body->airTicketListResponse;
$routings = $airTicketListResponse->routings;
Now we use foreach to loop through every routing and print the needed properties
foreach($routings as $routing){ //$routing will hold the object value in each loop
echo 'Airline '.$routing->mainAirlineName.'<br>';
echo 'Adult Base Price '.$routing->adultBasePrice.'<br>';
}
Getting single properties like the above is pretty straight forward, but for the information of the segments we would first need a nested foreach since we have multiple trips for each routing and then a second nested foreach since each trip has multiple segments
foreach($routings as $routing){ //$routing will hold the object value in each loop
echo 'Airline '.$routing->mainAirlineName.'<br>';
echo 'Adult Base Price '.$routing->adultBasePrice.'<br>';
foreach($routing->trips as $trip){
foreach($trip->segments as $index => $segment){
echo 'Segment '.$index.':<br>'
echo 'Depart From '.$segment->departureAirportCode.'<br>';
echo 'Departure Time '.$segment->departureTime.'<br>';
echo 'Duration '.$segment->duration.'<br>';
}
}
}
And that would be it. I hope my explanation was clear and you got the idea of how to traverse JSON objects
If you feel more comfortable working with an array than with an object to access your data [which might be where you're getting confused here] then you can use json_decode with an additional argument:
$data = json_decode($result, true);
This will leave you with an array ($data) containing all your flight information, you can then var_dump() it and see the hierarchy you're dealing with and loop through it.

Foreach() value is set, after value disappears

I am trying to add a new key to an existing numerical indexed array using a foreach() loop.
I wrote this piece of code:
foreach($new['WidgetInstanceSetting'] as $row){
$row['random_key'] = $this->__str_rand(32, 'alphanum');
debug($row);
}
debug($new);
The first debug() works as I expected: the 'random_key' is created in the $new array.
Now, the problem is that the second debug() shows the $new array, but without the newly added key.
Why is this happening? How can I solve this problem?
$row ends up being a copy in the scope of the foreach block, so you really are modifying a copy of it and not what's in the original array at all.
Stick a & in your foreach to modify the $row array within your $new array by reference:
foreach($new['WidgetInstanceSetting'] as &$row){
And as user576875 says, delete the reference to $row in case you use that variable again to avoid unwanted behavior, because PHP leaves it around:
foreach($new['WidgetInstanceSetting'] as &$row){
$row['random_key'] = $this->__str_rand(32, 'alphanum');
debug($row);
}
unset($row);
debug($new);
Use the & to get a by reference value that you can change.
foreach($new['WidgetInstanceSetting'] as &$row){
$row['random_key'] = $this->__str_rand(32, 'alphanum');
debug($row);
}
debug($new);
You need to access the element by reference if you want to modify if within the array, as follows:
foreach($new['WidgetInstanceSetting'] as &$row) {
$row['random_key'] = $this->__str_rand(32, 'alphanum');
}
you are not creating random_key in $new array you are creating it in $row

Categories