php- why traversing multidimensional array inside the foreach() doesnt work - php

I"m trying to traverse on an object i"m getting from openweather.com
without the foreach() i"m getting the right result. inside the foreach() i get an error.
the php code:
$contents = file_get_contents($url);
$clima=json_decode($contents,TRUE);
echo $clima['list'][5]['main']['temp']; // this one works
$i=0;
foreach($clima['list'] as $clima1) {
echo $clima1[$i]['dt']; // here i get PHP Notice: Undefined offset
echo $clima1[$i]['main']['temp']; //here i get PHP Notice: Undefined index: list
$i=$i+1;
}
the error that i get is:
PHP Notice: Undefined offset: 0 // the error is from 0 to 39 and there are 39 objects...
PHP Notice: Undefined index: list
the object beginning and ending part for sample:
Array ( [cod] => 200 [message] => 0.014 [cnt] => 40 [list] =>
Array ( [0] => Array ( [dt] => 1492732800 [main] => Array ( [temp] => 17.64 [temp_min] => 17.04 [temp_max] => 17.64 [pressure] => 1026.03 [sea_level] => 1031.21 [grnd_level] => 1026.03 [humidity] => 100 [temp_kf] => 0.6 ) [weather] => Array ( [0] => Array ( [id] => 800 [main] => Clear [description] => clear sky [icon] => 01n ) ) [clouds] => Array ( [all] => 0 ) [wind] => Array ( [speed] => 1.66 [deg] => 81.5008 ) [sys] => Array ( [pod] => n ) [dt_txt] => 2017-04-21 00:00:00 )
[38] => Array ( [dt] => 1493143200 [main] => Array ( [temp] => 19.72 [temp_min] => 19.72 [temp_max] => 19.72 [pressure] => 1026.92 [sea_level] => 1032.02 [grnd_level] => 1026.92 [humidity] => 87 [temp_kf] => 0 ) [weather] => Array ( [0] => Array ( [id] => 800 [main] => Clear [description] => clear sky [icon] => 01n ) ) [clouds] => Array ( [all] => 0 ) [wind] => Array ( [speed] => 6.95 [deg] => 10.5008 ) [sys] => Array ( [pod] => n ) [dt_txt] => 2017-04-25 18:00:00 )
[39] => Array ( [dt] => 1493154000 [main] => Array ( [temp] => 18.43 [temp_min] => 18.43 [temp_max] => 18.43 [pressure] => 1026.75 [sea_level] => 1031.91 [grnd_level] => 1026.75 [humidity] => 98 [temp_kf] => 0 ) [weather] => Array ( [0] => Array ( [id] => 800 [main] => Clear [description] => clear sky [icon] => 01n ) ) [clouds] => Array ( [all] => 0 ) [wind] => Array ( [speed] => 6.03 [deg] => 9.50076 ) [sys] => Array ( [pod] => n ) [dt_txt] => 2017-04-25 21:00:00 ) )
[city] => Array ( [id] => **** [name] => ***** [coord] => Array ( [lat] => **.**** [lon] => **.**** ) [country] => ** ) )
any help to understand my mistake will be appreciated

It seems, you loop "double". The counter inside the loop is the part, which you don't need, as you already loop over the array with foreach.
I think, the following code would be the better approach
$contents = file_get_contents($url);
$clima=json_decode($contents,TRUE);
echo $clima['list'][5]['main']['temp']; // this one works
foreach($clima['list'] as $clima1) {
echo $clima1['dt']; // here i get PHP Notice: Undefined offset
echo $clima1['main']['temp']; //here i get PHP Notice: Undefined index: list
}

That is because when you foreach over $clima['list'] you will get every values inside $clima['list']. Therefore, first, $clima1 = $clima['list'][0]. After that, $clima1 = $clima['list'][1]... Thus, $clima1 has neither 0 as an index nor 1 nor 2...
What you might do to see it more clearly is this :
foreach($clima['list'] as $key => $clima1)
And everytime, the $key will be your $id. Therefore, you can get rid of your $id and just do it like this :
foreach($clima['list'] as $id => $clima1)

When you run foreach($clima['list'] as $clima1) { ... each object in the loop ($clima1) is equal to $clima['list'][$i] so you don't need to manually put the $i in there.
If your really stuck I'd just run the loop like:
foreach($clima['list'] as $clima1) {
var_dump('<pre>' . $clima1 . '</pre>');
}
To see what the $clima1 variable really is.

Related

Why this array prints only last value outside of the loop? PHP

I am having this strange problem. I have a loop where I am looping through an array and executing a query for each id I get in the loop:
$select_deleted_arr=[];
foreach ($selected_devices as $devs) {
$select_deleted_devices->bind_param("i", $devs);
$select_deleted_devices->execute();
$select_deleted_devices_res = $select_deleted_devices->get_result();
$select_deleted_arr = $select_deleted_devices_res->fetch_all(MYSQLI_ASSOC);
}
$select_deleted_devices->close();
print_r($select_deleted_arr);
which prints :
Array ( [0] => Array ( [serial_imei] => 573 [serial_no] => 88888893 [name] => test device [device_no] => 1233 [barcode] => 44556633 ) )
return;
And when I print the array inside the loop:
Array ( [0] => Array ( [serial_imei] => 569 [serial_no] => 88888889 [name] => test device [device_no] => 1233 [barcode] => 44556633 ) ) Array ( [0] => Array ( [serial_imei] => 573 [serial_no] => 88888893 [name] => test device [device_no] => 1233 [barcode] => 44556633 ) )
I have no idea why is it behaving like this because I am doing exactly the same thing multiple times in my project but it always works perfectly fine. Any idea?

PHP - loop through messages in array

I have weird problem with my PHP code. I decoded an elasticsearch json, and I got this array:
Array ( [took] => 1 [timed_out] => [_shards] => Array ( [total] => 6 [successful] => 6 [skipped] => 0 [failed] => 0 ) [hits] => Array ( [total] => 7336 [max_score] => 0.8790647 [hits] => Array ( [0] => Array ( [_index] => logstash-2019.02.25 [_type] => doc [_id] => 5T8GJWkBAZbF3w3t4NF2 [_score] => 0.8790647 [_source] => Array ( [#version] => 1 [log-level] => ERROR [port] => 50906 [host] => 6b14cd1f183d.mynetwork [#timestamp] => 2019-02-25T14:20:01.367Z [Timestamp] => 2019-02-25T13:57:40+0000 [message] => Array ( [0] => 2019-02-25T13:57:40+0000 ERROR something happened in this execution. [1] => something happened in this execution. ) ) ) [1] => Array ( [_index] => logstash-2019.02.25 [_type] => doc [_id] => 7z8GJWkBAZbF3w3t4NF2 [_score] => 0.8790647 [_source] => Array ( [#version] => 1 [log-level] => INFO [port] => 50906 [host] => 6b14cd1f183d.mynetwork [#timestamp] => 2019-02-25T14:20:01.369Z [Timestamp] => 2019-02-25T14:00:13+0000 [message] => Array ( [0] => 2019-02-25T14:00:13+0000 INFO takes the value and converts it to string. [1] => takes the value and converts it to string. ) ) ) ) ) )
What I want is only to print the "messages".
If I run this code:
$echo json_decoded['hits']['hits']['0']['_source']['message']['0']
It echo "2019-02-25T13:57:40+0000 ERROR something happened in this execution."
And if I run this code:
$echo json_decoded['hits']['hits']['1']['_source']['message']['0']
It echo "2019-02-25T14:00:13+0000 INFO takes the value and converts it to string."
ALL GOOD SO FAR, but now I want to run it as loop, to print the messages. I made the following loop:
foreach($json_decoded['hits']['hits'] as $host) {
echo $host[$index]['_source']['message']['0'];
$index++;
}
I don't get any output. What is the problem?
When you foreach over ['hits']['hits'] this will iterate over the next level of the array (so the ['0'] and ['1'] elements). So you don't need to add in the [$index] part of your echo or the $index value...
foreach($json_decoded['hits']['hits'] as $host) {
echo $host['_source']['message']['0'];
}

search and unset array in array by value in php

My array look like this :
[cart_seller] => Array
(
[3] => Array
(
[หมวด1เลือก1 หมวด2เลือก1 1705] => Array
(
)
)
[4] => Array
(
[# 801] => Array
(
)
)
)
[cart_product] => Array
(
[หมวด1เลือก1 หมวด2เลือก1 1705] => Array
(
[id] => 1705
[name] => ทดสอบสินค้า
[image] => p1534937865-VASAVAT LAB N MEDIA LOGO W.png
[price] => 1111
[option] => หมวด1เลือก1 หมวด2เลือก1
[amount] => 1
)
[# 801] => Array
(
[id] => 801
[name] => โบว์แพรแถบ ร.9 ชนมพรรษา 84 พรรษา ปีพุทธศักราช 2554
[image] => p1498062217-ส.jpg
[price] => 90
[option] =>
[amount] => 1
)
)
I want unset '# 801' in cart_seller and cart_product
in cart_product use unset($cart['cart_product'][# 801]);
but in cart_seller it in array [4] what can i do without reference value (4) ?
exapmle unset($cart['cart_seller'][xxxx][# 801]);
Just loop cart seller array til you find #801.
foreach($cart['cart_seller'] as $key => $c){
if(array_key_exists("#801",$c)){
unset($cart['cart_seller'][$key]['#801']);
}
}

checking condition before foreach loop execution php

i want to check condition before for loop execution
this is my array
$rs=Array (
[0] => Array (
[questionID] => 47
[surveyID] => 51
[userID] => 31
[question_Title] => Choose Any One?
[question_Type] => Dropdown
[response] => 1.Android 2.Windows 3.Blackberry
[required] => 0
[add_time] => 0
)
[1] => Array (
[questionID] => 48
[surveyID] => 51
[userID] => 31
[question_Title] => Is it?
[question_Type] => Bigbox
[response] => Yes No
[required] => 1
[add_time] => 0
)
[2] => Array (
[questionID] => 129
[surveyID] => 51
[userID] => 31
[question_Title] => sELECT
[question_Type] => Single
[response] => DFG HBK GHCK HK
[required] => 0
[add_time] => 0
)
)
now i want to check if in $rs [required] => 1
then stop over all execution or $rs traversing using for each loop
rather from above example i want to stop executing first loop also.
Use array_column and achieve this functionality
Reference
http://php.net/manual/en/function.array-column.php
http://php.net/manual/en/function.array-search.php
Lower version array column function code
https://github.com/ramsey/array_column/blob/master/src/array_column.php
<?php
//assumed records is your array
$required = array_column($records, 'required');
if(FALSE===array_search('1', $required))
{
//value is not exist then process your loop
}
else
{
//required value is 1 then ignore the loop
}

Flatten Nested Array to a certain Key

I have a data structure like this
Array
(
[0] => Array
(
[actionResult] => Array
(
[show_page] => Array
(
[15] => Array
(
[section_page_id] => 15
[metadata_id] => 62
[section_id] => 7
[display_order] => 0
[current_layout] => 15
[behaviors] => a:1:{i:0;a:1:{i:0;a:0:{}}}
[options] => a:1:{s:13:"defaultLayout";i:63;}
[section_title] => Ask Study
)
[16] => Array
(
[section_page_id] => 16
[metadata_id] => 66
[section_id] => 7
[display_order] => 1
[current_layout] => 16
[behaviors] => a:0:{}
[options] => a:1:{s:13:"defaultLayout";i:67;}
[section_title] => Ask Study
)
[17] => Array
(
[section_page_id] => 17
[metadata_id] => 69
[section_id] => 7
[display_order] => 2
[current_layout] => 17
[behaviors] => a:0:{}
[options] => a:1:{s:13:"defaultLayout";i:70;}
[section_title] => Ask Study
)
[18] => Array
(
[section_page_id] => 18
[metadata_id] => 72
[section_id] => 7
[display_order] => 3
[current_layout] => 18
[behaviors] => a:0:{}
[options] => a:1:{s:13:"defaultLayout";i:73;}
[section_title] => Ask Study
)
)
)
)
[1] => Array
(
[actionResult] => Array
(
[view_page] => 18
)
)
)
What i need is the ability to flatten this to an array structure to a point where it stops at "actionResult" where all the actionResult will become ONE array rather than nested like this...
How can I go about by doing this in PHP???
if i have understood what you want correctly this should work:
$arr2=array();
foreach($arr as $tmp){
foreach($tmp as $actionRequest){
foreach($actionRequest as $key=>$val){
$arr2[$key]=$val;
}
}
}
where $arr is what you already have and $arr2 will be an array including 2 values , Show_Page and view_page
Best solution is:
$new_arr = array_map(function ($a) {
return $a['actionResult'];
}, $old_arr);

Categories