I have some JSON that I am trying to decode -- it is correctly extracting the value, but also generating an error.
Here is the var_dump:
["success"]=>
bool(true)
["providers"]=>
array(2) {
[0]=>
object(stdClass)#5 (15) {
["address1"]=>
string(14) "3240 W Lake St"
["address2"]=>
NULL
["city"]=>
string(11) "Minneapolis"
["crossStreet"]=>
string(26) "Lake Street & Market Plaza"
["description"]=>
string(55) "test location28402 description of services/prices/hours"
["distance"]=>
float(0.42900015862223)
["lat"]=>
float(44.948469)
["lon"]=>
float(-93.321155)
["name"]=>
string(17) "testlocation28402"
["phone"]=>
string(10) "6125551212"
["precise"]=>
bool(true)
["state"]=>
string(2) "MN"
["url"]=>
string(41) "http://www.testlocation28402.com?id=28402"
["urlCaption"]=>
string(25) "www.testlocation28402.com"
["zip"]=>
string(9) "554164512"
}
[1]=>
object(stdClass)#6 (15) {
["address1"]=>
string(19) "4335 Excelsior Blvd"
["address2"]=>
NULL
["city"]=>
string(16) "Saint Louis Park"
["crossStreet"]=>
NULL
["description"]=>
string(55) "test location26358 description of services/prices/hours"
["distance"]=>
float(0.91979730006713)
["lat"]=>
float(44.935773)
["lon"]=>
float(-93.33489)
["name"]=>
string(17) "testlocation26358"
["phone"]=>
string(10) "6125551212"
["precise"]=>
bool(true)
["state"]=>
string(2) "MN"
["url"]=>
string(41) "http://www.testlocation26358.com?id=26358"
["urlCaption"]=>
string(25) "www.testlocation26358.com"
["zip"]=>
string(9) "554164811"
}
}
["errors"]=>array(0) {
}
}
Above is the var_dump of the variable $json. I am trying to extract the CITY field with:
$json = json_decode($surescript);
foreach ($json as $providers){
foreach($providers as $onespot) {
echo "*";
echo $onespot->city;
echo "\n";
}
}
This outputs:
Warning: Invalid argument supplied for foreach() in /home/content/96/7973196/html/channels/MIL432/storeFinder_2.php on line 153
*Minneapolis
*Saint Louis Park
So, it is getting the correct nested variable, but also throwing off an error on the second foreach loop.
What am I doing incorrectly?
Thanks in advance for your help.
You're iterating over everything in the JSON in your outer loop, meaning that it's trying to parse the success section, the providers section, as well as the errors section.
When you try to parse the success, you can't iterate over the contents in the inner loop, hence the error. The errors section is an array, so you can iterate over it - since there's nothing in it, no error/warning for trying to access city, which wouldn't exist in it.
To only parse the providers:
$json = json_decode($surescript);
foreach ($json->providers as $provider){
echo "*";
echo $provider->city;
echo "\n";
}
Related
I'll go straight to the problem.
I have this array named
$datosUsuario['empleadoUsuario'] = $this->EmpleadoModel->get_empleado_vistaUsuario($result[0]->idusuario);
To show the values from datosUsuario
var_dump($datosUsuario['empleadoUsuario']);
The result speak by himself
array(1) { [0]=> object(stdClass)#26 (13) { ["nombreempresa"]=> string(7) "SERDIRH" ["email"]=> string(23) "luis.gomez#claro.com.ni" ["rutafoto"]=> string(24) "uploads/default-user.png" ["nombrecompleto"]=> string(24) "LUIS FELIPE GOMEZ ROBLES" ["carnetempleado"]=> string(6) "400387" ["direccion"]=> string(13) "SIN DIRECCION" ["telefono"]=> string(8) "88330377" ["dominioempleado"]=> string(10) "luis.gomez" ["fecha_ingreso"]=> string(10) "11/06/2012" ["nombreregion"]=> string(19) "CENTRO Y ESPECIALES" ["nombredepartamento"]=> string(4) "RAAS" ["nombretienda"]=> string(10) "BLUEFIELDS" ["idtienda"]=> int(81) } }
and when i try to obtain the value idtienda just gave me a NULL.
$data['idtienda'] = $empleadoUsuario[0]->idtienda;
Please tell me what im doing wrong.
The framework it's codeigniter.
Replace this
$data['idtienda'] = $empleadoUsuario[0]->idtienda;
with
$data['idtienda'] = $datosUsuario['empleadoUsuario'][0]->idtienda;
Ive had a lot of help reading some of the questions asked on this site so I figured I would post a question of my own. I've recently been messing around with arrays and was wondering how I would go about displaying certain items from an array I have.
array(1) { [0]=> array(4) { ["kind"]=> string(25) "youtube#videoListResponse" ["etag"]=> string(57) ""blahblah"" ["pageInfo"]=> array(2) { ["totalResults"]=> int(1) ["resultsPerPage"]=> int(1) } ["items"]=> array(1) { [0]=> array(5) { ["kind"]=> string(13) "youtube#video" ["etag"]=> string(57) ""blahblah"" ["id"]=> string(11) "XS6ysDFTbLU" ["snippet"]=> array(9) { ["publishedAt"]=> string(24) "2014-08-15T17:22:04.000Z" ["channelId"]=> string(24) "UCnEiGCE13SUI7ZvojTAVBKw" ["title"]=> string(35) "Bill Gates ALS Ice Bucket Challenge" ["description"]=> string(212) "Bill Gates accepts Mark Zuckerberg’s ALS Ice Bucket Challenge and nominates Elon Musk, Ryan Seacrest and Chris Anderson from TED to participate and raise awareness for ALS, also known as Lou Gehrig’s Disease." ["thumbnails"]=> array(5) { ["default"]=> array(3) { ["url"]=> string(46) "https://i.ytimg.com/vi/XS6ysDFTbLU/default.jpg" ["width"]=> int(120) ["height"]=> int(90) } ["medium"]=> array(3) { ["url"]=> string(48) "https://i.ytimg.com/vi/XS6ysDFTbLU/mqdefault.jpg" ["width"]=> int(320) ["height"]=> int(180) } ["high"]=> array(3) { ["url"]=> string(48) "https://i.ytimg.com/vi/XS6ysDFTbLU/hqdefault.jpg" ["width"]=> int(480) ["height"]=> int(360) } ["standard"]=> array(3) { ["url"]=> string(48) "https://i.ytimg.com/vi/XS6ysDFTbLU/sddefault.jpg" ["width"]=> int(640) ["height"]=> int(480) } ["maxres"]=> array(3) { ["url"]=> string(52) "https://i.ytimg.com/vi/XS6ysDFTbLU/maxresdefault.jpg" ["width"]=> int(1280) ["height"]=> int(720) } } ["channelTitle"]=> string(13) "thegatesnotes" ["categoryId"]=> string(2) "29" ["liveBroadcastContent"]=> string(4) "none" ["localized"]=> array(2) { ["title"]=> string(35) "Bill Gates ALS Ice Bucket Challenge" ["description"]=> string(212) "Bill Gates accepts Mark Zuckerberg’s ALS Ice Bucket Challenge and nominates Elon Musk, Ryan Seacrest and Chris Anderson from TED to participate and raise awareness for ALS, also known as Lou Gehrig’s Disease." } } ["statistics"]=> array(5) { ["viewCount"]=> string(8) "23231956" ["likeCount"]=> string(6) "206532" ["dislikeCount"]=> string(4) "4471" ["favoriteCount"]=> string(1) "0" ["commentCount"]=> string(5) "14548" } } } } }
so this is the array i'm trying to extract values from. Could someone maybe show me how to display the localized title, default thumbnail and viewcount with php. I think from there I can manage to get the rest figured out. Any help would be appreciated. Thanks
P.S.
I've tried to use the below code with no luck.
$MYarray = array($ARRAY_Data);
echo $MYarray['items'][0]['statistics']['viewCount'];
$ARRAY_Data holds the array I posted at the top.
It looks like the thing that's causing you problems is this:
$MYarray = array($ARRAY_Data);
That just adds another array around your original array, which doesn't seem like it should be necessary, and based on your var_dump output, if you hadn't done that, in the next line
echo $MYarray['items'][0]['statistics']['viewCount'];
you're actually already using the correct array keys to get you the value you want. So just skip the $MYarray = array($ARRAY_Data); and use the same keys on the original array:
echo $ARRAY_Data['items'][0]['statistics']['viewCount'];
Hello awesome programmers!
I am so sorry for the the novice question, however, I am having trouble finding a solution to my problem. I am attempting to run a for each loop through my array passed from my controller, however, the data being outputted is not the same as when I run a var_dump($array). I am thinking perhaps that I need to iterate through this object maybe? However, when I attempt to do so, I get a non-object error.
Controller:
$data['user_details'] = $this->ion_auth->user()->row();
View:
var_dump($user_details);
foreach($user_details as $item){
echo $item['email'];
}
The output of this is : "21nfn4111NR12" but should be roger#peterson.net!
I have also tried the object form:
var_dump($user_details);
foreach($user_details as $item){
echo $item->email;
}
However, it results in error trying to get property of non-object!
When I run the var dump I get the following:
object(stdClass)#21 (17) {
["id"]=>
string(1) "2"
["ip_address"]=>
string(14) "119.132.127.01"
["username"]=>
string(12) "roger petereson"
["password"]=>
string(40) "fdZxF/RQo4nZKmbA5XQlwefbc8f8e5c74899c3d0"
["salt"]=>
NULL
["email"]=>
string(19) "roger#peterson.net"
["activation_code"]=>
NULL
["forgotten_password_code"]=>
NULL
["forgotten_password_time"]=>
NULL
["remember_code"]=>
string(22) "44hjOlloLTIrkSrjSBVNie"
["created_on"]=>
string(10) "1404939094"
["last_login"]=>
string(10) "1405099607"
["active"]=>
string(1) "1"
["first_name"]=>
string(6) "Roger"
["last_name"]=>
string(5) "Peterson"
["is_owner"]=>
string(1) "1"
["user_id"]=>
string(1) "2"
}
The following line:
$this->ion_auth->user()->row();
returns an object not an array (check your var_dump output), so you just need to
echo $user_details->email;
I'm trying to get the values of a sub array out in a foreach loop.
I looked at this example as it seemed really relevant to my problem, but unfortunately I've not been able to get it to work, and I'm hoping someone here can pick up where I've gone wrong.
PHP foreach not working with sub-array
I have an array called $booked and inside that array I have a sub array $booked['30_booked'].
Within that second array there are multiple values, such as title, name, address etc.
My code currently looks like this:
foreach($booked['30_booking'] as $new_var){
var_dump('</br>', $booked['30_booking']);
var_dump('</br>', $new_var);
var_dump($new_var['title'], $new_var->title, $booked['30_booking']->title); exit();
}
I've output the data as you can see above in var_dump statements to try and get one of these methods to work.
Unfortunately nothing within $new_var is pulling out the title, but $booked['30_booking']->title
Have I not put it into the foreach statement correctly?
All help appreciated - thanks!
EDIT:
Main array output snippet:
array(6) { ["30_booked"]=> object(stdClass)#21 (34) { ["id"]=> string(2) "30" ["title"]=> string(2) "Ms" ["firstname"]=> string(5) "FIRST NAME" ["surname"]=> string(9) "LAST NAME" ["address"]=> string(6) "- -- -" ["postcode"]=> string(7) "FAK E99" ["country"]=> string(14) "United Kingdom" ["phone"]=> string(11) "01221111111" ["alt_phone"]=> string(0) "" ["email"]=> string(25) "fake#fake.co.uk" ["notes"]=> string(8) "FAKE DEAL" } }
EDIT 2:
Sub Array $booked['30_booking'] snippet:
object(stdClass)#21 (34) { ["id"]=> string(2) "30" ["title"]=> string(2) "Ms" ["firstname"]=> string(5) "FIRST NAME" ["surname"]=> string(9) "LAST NAME" ["address"]=> string(6) "- -- -" ["postcode"]=> string(7) "FAK E99" ["country"]=> string(14) "United Kingdom" ["phone"]=> string(11) "01221111111" ["alt_phone"]=> string(0) "" ["email"]=> string(25) "fake#fake.co.uk" ["notes"]=> string(8) "FAKE DEAL" }
EDIT 3:
My var_dump of the $new_var by itself is bringing back the value of the id - but when I try and get the second value out the sub array "title" it doesn't return anything.
FINAL FIX:
Thanks to Kita I realised I was returning a std class object and not a second array, something that I stupidly missed the first time round. Because of that I can't actually foreach on the object.
Which led me to this post which will help me fix the issue:
PHP foreach array with stdClass Object
Thank you very much for all your help!!!
You expected an array inside $booked['30_booking'] but in fact there was a stdClass object.
array(6) {
["30_booked"]=> object(stdClass)#21 (34) {
["id"]=> string(2) "30"
["title"]=> string(2) "Ms"
["firstname"]=> string(5) "FIRST NAME"
["surname"]=> string(9) "LAST NAME"
["address"]=> string(6) "- -- -"
["postcode"]=> string(7) "FAK E99"
["country"]=> string(14) "United Kingdom"
["phone"]=> string(11) "01221111111"
["alt_phone"]=> string(0) ""
["email"]=> string(25) "fake#fake.co.uk"
["notes"]=> string(8) "FAKE DEAL"
}
//I assume you have left out the other array elements from the Main array snippet.
}
Getting stdClass instead of array usually happens when you parse a JSON string with json_decode() without the second parameter.
// without second parameter
var_dump( json_decode( '{"id":"30"}' ) );
object(stdClass)#1 (1) {
["id"]=>
string(2) "30"
}
// 'true' as second parameter
var_dump( json_decode( '{"id":"30"}', true ) );
array(1) {
["id"]=>
string(2) "30"
}
Above examples are hosted at: http://ideone.com/GNMRlD
Since stdClass object itself does not provide iteration functionality, using it with foreach will yield errors.
You can convert stdClass into array with functions such as http://www.if-not-true-then-false.com/2009/php-tip-convert-stdclass-object-to-multidimensional-array-and-convert-multidimensional-array-to-stdclass-object/ .
For eg. if your array looks like below. foreach which I used will be working
$new_array = array(array('total'=>array('title'=>'test','text'=>'text')));
foreach ($new_array as $val)
{
print_r($val['total']['title']); // Use this for array
print_r($val->total->title); // Use this for object
}
if your array looks like below. Use the below foreach.
$new_array = array(array('total'=>array(array('title'=>'test','text'=>'text'),array('title'=>'test1','text'=>'text1'))));
foreach ($new_array as $val)
{
foreach($val['total'] as $new_val)
{
print_r($new_val['title']);
}
}
You can try this, I hope that helps you
foreach($booked as $new_var){
var_dump('</br>', $new_var);
var_dump('</br>',$new_var['30_booking']->title);
}
I think in your foreach there is mistake of word 30_booking
since in your main array out put display it shows 30_booked
check that also
Okay, so I'm writing an app that allows me to see steam data from a database of whoever registered.
I met a problem. Firstly, the steam API for multiple users is not standardized. (e.g. everytime you refresh this, the position of user changes (What kind of API does this?!)
Since steam does not standardize the API, I'll have to do it myself, so after doing a json_decode($url, true). It is not an assoc array.
I want to sort the assoc array by the steam ID (which is numeral) and match them against my own database of user (also contains steam ID, but can be sorted in the database), so how do I go about doing that?
E.g.
Array 1:
array(3) {
[0]=>
array(2) {
["steam_id32"]=>
string(17) "76561198025035234"
["name"]=>
string(7) "Mitsuki"
}
[1]=>
array(2) {
["steam_id32"]=>
string(17) "76561197968270056"
["name"]=>
string(3) "nrn"
}
[2]=>
array(2) {
["steam_id32"]=>
string(17) "76561197982490298"
["name"]=>
string(4) "Ximp"
}
}
Array 2:
array(1) {
["response"]=>
array(1) {
["players"]=>
array(3) {
[0]=>
array(16) {
["steamid"]=>
string(17) "76561197982490298"
["communityvisibilitystate"]=>
int(3)
["profilestate"]=>
int(1)
["personaname"]=>
string(53) "……‮‮‮‮‮‮‮‮‮‮Ximp ……FUS RO DAH"
["lastlogoff"]=>
int(1328569605)
["profileurl"]=>
string(34) "http://steamcommunity.com/id/ximp/"
["avatar"]=>
string(114) "http://media.steampowered.com/steamcommunity/public/images/avatars/f8/f8ee0cf00a2ec20417bf5b26b99fd6fb4dc176c1.jpg"
["avatarmedium"]=>
string(121) "http://media.steampowered.com/steamcommunity/public/images/avatars/f8/f8ee0cf00a2ec20417bf5b26b99fd6fb4dc176c1_medium.jpg"
["avatarfull"]=>
string(119) "http://media.steampowered.com/steamcommunity/public/images/avatars/f8/f8ee0cf00a2ec20417bf5b26b99fd6fb4dc176c1_full.jpg"
["personastate"]=>
int(1)
["realname"]=>
string(9) "I life in"
["primaryclanid"]=>
string(18) "103582791430354400"
["timecreated"]=>
int(1146939839)
["gameextrainfo"]=>
string(20) "The Binding Of Isaac"
["gameid"]=>
string(6) "113200"
["loccountrycode"]=>
string(2) "DE"
}
[1]=>
array(14) {
["steamid"]=>
string(17) "76561197968270056"
["communityvisibilitystate"]=>
int(3)
["profilestate"]=>
int(1)
["personaname"]=>
string(3) "nrn"
["lastlogoff"]=>
int(1328618220)
["profileurl"]=>
string(34) "http://steamcommunity.com/id/nrnx/"
["avatar"]=>
string(114) "http://media.steampowered.com/steamcommunity/public/images/avatars/50/50b908e0aa2c730fa0f68ab0afc8b04fddb133f1.jpg"
["avatarmedium"]=>
string(121) "http://media.steampowered.com/steamcommunity/public/images/avatars/50/50b908e0aa2c730fa0f68ab0afc8b04fddb133f1_medium.jpg"
["avatarfull"]=>
string(119) "http://media.steampowered.com/steamcommunity/public/images/avatars/50/50b908e0aa2c730fa0f68ab0afc8b04fddb133f1_full.jpg"
["personastate"]=>
int(1)
["realname"]=>
string(9) "Nathaniel"
["primaryclanid"]=>
string(18) "103582791432850562"
["timecreated"]=>
int(1092771678)
["loccountrycode"]=>
string(2) "US"
}
[2]=>
array(14) {
["steamid"]=>
string(17) "76561198025035234"
["communityvisibilitystate"]=>
int(3)
["profilestate"]=>
int(1)
["personaname"]=>
string(23) "[ProudiA] Mitsuki Sakai"
["lastlogoff"]=>
int(1328621807)
["commentpermission"]=>
int(1)
["profileurl"]=>
string(42) "http://steamcommunity.com/id/mitsukisakai/"
["avatar"]=>
string(114) "http://media.steampowered.com/steamcommunity/public/images/avatars/9d/9d279f349422cbbed55adf1c8eabb0924ea0a719.jpg"
["avatarmedium"]=>
string(121) "http://media.steampowered.com/steamcommunity/public/images/avatars/9d/9d279f349422cbbed55adf1c8eabb0924ea0a719_medium.jpg"
["avatarfull"]=>
string(119) "http://media.steampowered.com/steamcommunity/public/images/avatars/9d/9d279f349422cbbed55adf1c8eabb0924ea0a719_full.jpg"
["personastate"]=>
int(1)
["realname"]=>
string(12) "酒井å‚è¼"
["primaryclanid"]=>
string(18) "103582791432752089"
["timecreated"]=>
int(1273714689)
}
}
}
}
For sortig array you can find a list of all function that you need here
Update:
first you must create a 1d array from a 2d or 3d you can use this code to make an easy access array and sortable (this an example):
<?php
$inArr;//This is the 2D array
$outArr = array();
for($i=0;$i<count($inArr);$i++){
$outArr[$i] = $inArr[$i][0];
?>
then you can sort it with ksort() or krsort() function.and for adding an array to another :
<?php
$stack = array("value1", "value2");
array_push($stack, "value3", "value4");
print_r($stack);
?>