Bug when trying to update an array - php

I have a two questions with a symfony's project.
My first one :
I am trying to modify some data in an array.
I have this code
var_dump($results); // FIRST ONE
foreach ($results as $result) {
foreach ($result as $res) {
foreach ($dates as $date) {
if(!array_key_exists($date,$res)) {
$res = array_merge($res,[$date => '0']);
}
}
var_dump($res); // THIS ONE IS MODIFIED
}
}
var_dump($results); // LAST ONE... SAME AS THE FIRST ONE
I don't understand why my array ' $results ' is no updated... am i missing something ?
And my second question : is there any way to simplify this code ? I don't like the 3 foreach.
Thanks you guys :)

PHP foreach copy each item when iterate so $result array will not update when you change $res item.
1) You can use array keys to change main array
foreach($arrr as $k => $item) {arrr[$k]['key'] = 'changed'}
2) Or you can get link to the $res item and change it dirrectly
foreach($arrr as &$item) {$item['key'] = 'changed'}
Note that second case can cause different issues

Unless you're passing an object in PHP, PHP does not pass values by reference. $res is a copy of the value, not a link to the original value. If you know what you're doing, you can pass by reference. When passing by reference, altering $res would alter the original data. You pass by reference by prefixing a & to the variable or argument.
Since this is a nested foreach, you'll also have to pass $result by reference to avoid that being a copy of the item of $results.
foreach ($results as &$result) {
foreach ($result as &$res) {
foreach ($dates as $date) {
if(!array_key_exists($date,$res)) {
$res = array_merge($res,[$date => '0']);
}
}
}
}

Related

Creating arrays within arrays without creating keys first

This is how I used to create keys that didn't exist inside an array when looping through data:
$array = [];
foreach ($results as $result) {
if (!isset($array[$result->id])) {
$array[$result->id] = [];
}
$array[$result->id][] = $result->value;
}
A colleague at work does the following. PHP doesn't error but I am not sure if it's a feature of PHP or if it's incorrect:
$array = [];
foreach ($results as $result) {
$array[$result->id][] = $result->value;
}
Is it incorrect for me to do the above?
if condition you put in your code is unnecessary. Let me explain.
if (!isset($array[$result->id])) {
$array[$result->id] = [];
}
This mean if $array[$result->id] is not exist than you are define it as an array, however $array[$result->id][] it self create new array if not existing without throwing any error. So no need to use if condition error. In conclusion, both code are correct, just you are using unnecessary if condition.

Merging two queries to one JSON object

I have two queries:
1) $result = $this->_db->get_where("wishes",array("is_open"=>1))->result_array();
2) $requirements_result = $this->_db->get("requirements")->result_array();
I'm trying to output the data in this JSON format:
{
[
{
id:12,
title:"Meet Messi",
image_url:"http://dsadsa.dsadsa",
previewImageUrl:"http://kdjfla.com"
is_open:"true"
requirements: [
{
id: 123,
title:"kiss Messi",
is_complete: true
}
]
}
]
}
}
I created two models (one for each query).
This is what I've done so far:
$result = $this->_db->get_where("wishes",array("is_open"=>1))->result_array();
$requirements_result = $this->_db->get("requirements")->result_array();
$return_array = array();
foreach ($result as $value)
{
$wishes_model = new wishes_model();
$wishes_model->init_wishes($value);
$return_array[] = $wishes_model;
}
return $return_array;
How to i insert the requirements result to create this JSON?
First, create your wishes array as an associative array, with the ID as the key:
$wishes_array = array();
foreach ($results as $value) {
$wishes_model = new wishes_model();
$wishes_model->init_wishes($value);
$wishes_array[$value['id']] = $wishes_model;
}
Then you can add the requirements to the appropriate wish:
foreach ($requirements_results as $req) {
$wishes_array[$req['wish_id']]->requirements[] = $req;
}
I'm making some assumptions about which things in your application are associative arrays versus objects. You should be able to adjust this to match your specific implementation.
I have couple of question but for now i am gonna guess.
You can try array_merge but it will overwrite same keys.
If you don't want that you can add prefix to keys and then merge both array.
And i think rest of the solutions you already have in here.
Hi like you have 2 results say result1 and result2
you can make 2 foreach loop for each and store them in two different array and then
you make pass it in result and encode it.
see how it works:
foreach ($result1 as $res)
{
$result_s1[]=$res;
}
foreach($result2 as $cmd)
{
result_s1[]=$cmd;
}
$resultdata[]=array_merge($result_s1,$result_s2)

PHP: String in json parse

I am trying to parse a json. I am running this in a foreach loop and if I do the following it works:
$places = array('restaurant', 'store', 'etc')
foreach ($this->placesCachingTypes as $places) {
$places_location_lat = $json_decoded->json[0]->restaurant[0]->geometry->location->lat;
$places_location_lng = $json_decoded->json[0]->restaurant[0]->geometry->location->lng;
}
However, when I do the following, i.e. I change restaurant to $places (I need to do this since I have an array of different places and I want to parse all of them in a foreach loop) it doesn't work.
foreach ($this->placesCachingTypes as $places) {
$places_location_lat = $json_decoded->json[0]->$places[0]->geometry->location->lat;
$places_location_lng = $json_decoded->json[0]->$places[0]->geometry->location->lng;
}
Solution is changing $places to {$places}[0]
The $places array contains keywords, such as restaurant or store. So the [0] is referring to the first one in the json which is why it's needed.
Why do you have this in the first loop:
json[0]->restaurant[0]
json[0]->$restaurant[0]
But then in the next you have:
json[0]->$places[0]
json[0]->$places[0]
Perhaps you are parsing the JSON incorrectly and it should be:
foreach ($this->placesCachingTypes as $places) {
$places_location_lat = $json_decoded->json[0]->places[0]->geometry->location->lat;
$places_location_lng = $json_decoded->json[0]->places[0]->geometry->location->lng;
}
And then in the first loop, you should do a similar edit to get rid of $restaurant[0]:
foreach ($this->placesCachingTypes as $places) {
$places_location_lat = $json_decoded->json[0]->restaurant[0]->geometry->location->lat;
$places_location_lng = $json_decoded->json[0]->restaurant[0]->geometry->location->lng;
}
Then again, unclear on what value $places has when you loop via foreach ($this->placesCachingTypes as $places) {. It does’t make sense what you would be looping through with the value of $places. And perhaps assigning that $places in the loop object of $json_decoded->json[0]-> is the source of your issues? Need more info from you to confirm this.

Updating and Sorting a Multidimensional PHP Array

I have a mySQL query that dumps into an array, is sorted and then displayed, and that works perfectly.
My problem is that I want to update these values, re-sort them and display. I've been able to update the values, but it's within the same for loop and so it doesn't re-sort. So then I close the loop and re-sort but it doesn't save the updates I made in the first loop. Help is much appreciated.
foreach ($arr as $mks){
if ($mks['Column1']==$Var) {$mks['Column2'] = $mks['Column2'] + 1;
}
My sorting code
foreach ($arr as $mks){
echo $mks['Column1'] . ", " . $mks['Column2'] . "<br>";
}
How do I get this to re-save into my array properly?! I've tried googling this for most of the morning but has lead to frustration.
I think this is what you need:
foreach ($arr as $key => $mks){
if ($mks[$key] == $Var) {
$arr[$key] = $mks+1;
}
}
Now, $arr will contain the modified array, and you can use / modify it further as you need.
I don't see any "sorting code" but you can try to use references "&" instead of copy vars in your foreach(s) :
foreach($arr as & $mks){
...
}
Instead of copying your cells it will to give you a reference and every modifications done on it will be saved in the array.
Try changing your array like this instead
foreach ($arr as $key => $mks){
if ($mks['Column1']==$Var) {$arr[$key]['Column2'] = $mks['Column2'] + 1;
}

how to add another attribute using foreach loop to an array of rows

I am using a foreach loop on an array of rows in a model file in CodeIgniter.
What i want to do is reflect the changes i make in every row ,in the foreach loop ,to the original array.
$unique = $this->db->get_where('list', array('item_index' => $item));
foreach ($unique->result_array() as $row)
{
$row["status"]= "Not Unique";
if($row["bid_amount"]==$amount)
{
if($count==0){ $row["status"]="Unique and Final"; }
else {$row["status"]="Unique but Not Final"; }
}
$count++;
}
return $unique;
I am adding another attribute to each row here and i want to echo this attribute corresponding to each row in a view file.
But i am getting error Undefined index: status.
How can i possibly reflect the changes in the array to be returned.
Assign the result_array() to a variable, iterate over it, but change the original array and not the local one. PHP's foreach comes in two flavours:
foreach($arr as $value) and foreach($arr as $key => $value)
Try this:
$results = $unique->result_array();
foreach ($results as $rK => $rV){
$results[$rK]["status"]= "Not Unique";
//other stuff.
}
return $results;
Alternatively, you can pass by reference:
foreach ($results as &$result) {
$result['status'] = "Not Unique";
}
See the PHP docs on arrays. Specifically Example 10.
In your foreach the $row refers to a variable that's local to the loop. Thus changing it does not affect the data in $unique.

Categories