I have a json file which I want to get the data from and use it as php variables inside of a loop.
I keep getting Undefined index erros and it just does not work...
This is my code:
$file = file_get_contents("csv/products.json",'r');
for($i=0;$i<18;$i++){
$datosArray = json_decode($file,true);
//var_dump($datosArray);
if (isset ($datosArray)){
$id = $datosArray["id"];
$genderid = $datosArray["sex_id"];
$dest = $datosArray["destaque"];
$cat = $datosArray["categoria"];
$marc = $datosArray["Marca"];
$name = $datosArray["nombre"];
$desc = $datosArray["descripcion"];
$pho1 = $datosArray["photo_id1"];
$pho2 = $datosArray["photo_id2"];
$pho3 = $datosArray["photo_id3"];
$dprice = $datosArray["D_price"];
$oprice = $datosArray["O_price"];
}
?>
This is what part of my json looks like:
[
{
"id": 1,
"sex_id": 101,
"destaque": 1,
"categoria": "Vestidos",
"Marca": "Marfinno",
"nombre": "Mono rayas",
"descripcion": "Mono de rayas con botones y amarre Marfinno",
"photo_id1": "Female1.jpg",
"photo_is2": "Female1.1.jpg",
"photo_id3": "Female1.2.jpg",
"D_price": "$100.00",
"O_price": "$300.00"
},
{
"id": 2,
"sex_id": 101,
"destaque": 0,
"categoria": "Vestidos",
"Marca": "Marfinno",
"nombre": "Mono liso",
"descripcion": "Mono liso con amarre Marfinno",
"photo_id1": "Female2.jpg",
"photo_is2": "Female2.1.jpg",
"photo_id3": "Female2.2.jpg",
"D_price": "$100.00",
"O_price": "$300.00"
},
Thank you.
There is a mistake here:
$file = file_get_contents("csv/products.json",'r');
Simply put:
$file = file_get_contents("csv/products.json");
file_get_contents does not require a 'r' argument like when you open a file. See https://www.php.net/manual/en/function.file-get-contents.php
Then from the comment about the var_dump, you have to see that you have an array of arrays.
array(54) {
[0]=> array(12) {
["id"]=> int(1)
["sex_id"]=> int(101)
["destaque"]=> int(1)
["categoria"]=> string(8) "Vestidos"
["Marca"]=> string(8) "Marfinno"
["nombre"]=> string(10) "Mono rayas"
["descripcion"]=> string(44) "Mono de rayas con botones y amarre Marfinno"
["photo_id1"]=> string(11) "Female1.jpg"
["photo_is2"]=> string(13) "Female1.1.jpg"
["photo_id3"]=> string(13) "Female1.2.jpg"
["D_price"]=> string(7) "$100.00"
["O_price"]=> string(7) "$300.00"
}
[1]=> array(12) {
....
}
So when you want to reference an item, you have to put 2 indexes:
...
$id = $datosArray[$i]["id"];
$genderid = $datosArray[$i]["sex_id"];
...
This will work if you keep that portion of code inside the context of the for loop.
Related
When I encode the json data fetching from the mysql database, I get this:
[{"userid":"11","postid":"12"},{"userid":"13","postid":"12"},{"userid":"16","postid":"12"}]
And I am trying to get only the userid's like this: 11, 13, 16.
Decoding the json data gives me an output of: Array. And nothing else. When I var_dump this is my results:
array(3) {
[0]=> array(2) {
["userid"]=> string(2) "11"
["postid"]=> string(2) "12"
}
[1]=> array(2) {
["userid"]=> string(2) "13"
["postid"]=> string(2) "12"
}
[2]=> array(2) {
["userid"]=> string(2) "16"
["postid"]=> string(2) "12"
}
So I know there is data present, it's just not showing for some reason.
Here is what my query looks like:
if(isset($_POST['postuserid'])){
$uid = $_POST['postuserid'];
$ssql = "SELECT * FROM foodid WHERE postid=$uid";
$rresult = mysqli_query($db,$ssql);
while ($lrow = mysqli_fetch_assoc($rresult)){
$ret[] = $lrow;
$postjson = json_encode($ret);
$decode_postid = json_decode($postjson, true);
$new_postid = $decode_postid;
}
var_dump($new_postid);
die($new_postid);
// die($new_postid['userid']); is what I need along with all data userid fetched.
}
Is there a reason why this works when I encode json data, but not when I decode the json data?
Are you trying to get that array out of the die function? It can only take a string or int.
http://php.net/manual/en/function.exit.php
Your array is there... just do something like:
$ids = '';
foreach ($new_postid as $post) {
$ids .= $post['userid'] . ',';
}
$ids = rtrim($ids,',');
die($ids);
Try mapping those results:
$new_postid = $decode_postid;
$new_postid = array_map(function($item){
return $item['userid'];
}, $new_postid);
var_dump($new_postid);
Output
array(3) {
[0]=>
string(2) "11"
1=>
string(2) "13"
[2]=>
string(2) "16"
}
If you need to output as string, just use implode function
die(implode(',',$new_postid));
http://php.net/manual/en/function.array-map.php
here i have one array in this array i want to make json,i tried but i am unable to get the exact format what i want,any one please help me,
This my array
var_dump($absentresponse);
array(1) {
[0]=>
array(9) {
["absendId"]=>
string(1) "1"
["studentAbsentId"]=>
string(9) "["1","2"]"
["studentAbsentDate"]=>
string(10) "2017-04-11"
["schoolId"]=>
string(1) "2"
["classId"]=>
string(1) "1"
["sectionId"]=>
string(1) "1"
["reg_date"]=>
string(19) "2017-04-13 01:01:03"
["created_by"]=>
string(29) "kanniyappan#g2evolution.co.in"
["status"]=>
string(1) "0"
}
}
My expected results
{
"status": 1,
"data":
[
{
"studentabsentId":"1"
"studentAbsentDate": "2017-04-12"
},
{
"studentabsentId":"2"
"studentAbsentDate": "2017-04-12"
}
]
}
My Update Code
$json_response = json_encode($absentresponse); echo $json_response;
[
{
"absendId": "1",
"studentAbsentId": "[\"1\",\"2\"]",
"studentAbsentDate": "2017-04-11",
"schoolId": "2",
"classId": "1",
"sectionId": "1",
"reg_date": "2017-04-13 01:01:03",
"created_by": "kanniyappan#g2evolution.co.in",
"status": "0"
}
]
I think there is some wrong format in your array. Please recheck on index studentAbsentId, I think that should be an array, not a string. Below is my code if we assume that value of studentAbsentId is an array of student ID.
$newArray = array();
$newArray['status'] = $absentresponse['status'];
$newArray['data'] = array();
foreach($absentresponse['studentAbsentId'] as $id){
$data['studentabsentId'] = $id;
$data['studentAbsentDate'] = $absentresponse['studentAbsentDate'];
$newArray['data'][] = $data;
}
$json = json_encode($newArray);
$absentresponse = array();
$data['status'] = 1;
foreach ($absentresponse as $key => $value) {
$row = array();
$row['absendId'] = $value['absendId'];
$row['studentAbsentId'] = $value['studentAbsentId'];
$row['studentAbsentDate'] = $value['studentAbsentDate'];
$row['schoolId'] = $value['schoolId'];
$row['classId'] = $value['classId'];
$row['sectionId'] = $value['sectionId'];
$row['reg_date'] = $value['reg_date'];
$row['created_by'] = $value['created_by'];
$data['data'][] = $row;
}
echo json_encode($data);
Please try below code:
$json_response = json_encode($absentresponse);
echo $json_response;
$absentresponse_json = json_encode($absentresponse);
Unless I'm not understanding your question, that should do it.
I have JSON data:
[
{
"title": "red",
},
{
"title": "blue",
},
{
"title": "yellow",
},
]
I want to get only first data, red.
I try with this
...
$json_output=curl_exec($ch);
$mydata = json_decode($json_output);
$result = $mydata->title;
echo $result[1];
and
$result = $mydata->title[1];
but dont work.
How i can get only first "title" data from this json?
$json_output=curl_exec($ch);
$mydata = json_decode($json_output);
$result = $mydata[0]->title;
echo $result;
According to PHP's manual, json_decode returns the value encoded in JSON in appropriate PHP type. Values true, false and null are returned as TRUE, FALSE and NULL respectively. NULL is returned if the JSON cannot be decoded or if the encoded data is deeper than the recursion limit.
<?php
$json_output = '[{ "title": "red" }, { "title": "blue" }, { "title": "yellow" }]';
$mydata = json_decode($json_output);
var_dump($mydata);
/* Output:
array(3) {
[0]=>
object(stdClass)#1 (1) {
["title"]=>
string(3) "red"
}
[1]=>
object(stdClass)#2 (1) {
["title"]=>
string(4) "blue"
}
[2]=>
object(stdClass)#3 (1) {
["title"]=>
string(6) "yellow"
}
}
*/
echo $mydata[0]->title;
// Output: red
?>
When 2nd parameter is TRUE, returned objects will be converted into associative arrays.
<?php
$json_output = '[{ "title": "red" }, { "title": "blue" }, { "title": "yellow" }]';
$mydata = json_decode($json_output, TRUE);
var_dump($mydata);
/* Ouput:
array(3) {
[0]=>
array(1) {
["title"]=>
string(3) "red"
}
[1]=>
array(1) {
["title"]=>
string(4) "blue"
}
[2]=>
array(1) {
["title"]=>
string(6) "yellow"
}
}
*/
echo $mydata[0]['title'];
// Output: red
?>
On a side note, accessing elements within an object that contain any character not allowed under PHP's naming convention can be done by wrapping the index with a curly bracket.
<?php
$json_output = '[{ "h1-title": "red" }, { "h1-title": "blue" }, { "h1-title": "yellow" }]';
$mydata = json_decode($json_output);
var_dump($mydata);
/* Output:
array(3) {
[0]=>
object(stdClass)#1 (1) {
["h1-title"]=>
string(3) "red"
}
[1]=>
object(stdClass)#2 (1) {
["h1-title"]=>
string(4) "blue"
}
[2]=>
object(stdClass)#3 (1) {
["h1-title"]=>
string(6) "yellow"
}
}
*/
echo $mydata[0]->{'h1-title'};
// Output: red
?>
First of all your JSON is not valid. You can use this validator to check if your JSON is valid. It should look like the following:
[
{
"title": "red"
},
{
"title": "blue"
},
{
"title": "yellow"
}
]
There are two ways of accessing the JSON object:
Array of objects:
$mydata = json_decode($json_output);
$title = $mydata[0]->title; // red
Associative array:
$mydata = json_decode($json_output, true);
$title = $mydata[0]['title']; // red
See json_decode() for more information.
I'm using the following PHP code to return a json string:
$itemURL = 'http://***.***.***/search?tag=Football&affiliate_id=&max_results=3';
$response = file_get_contents($itemURL);//curl_exec($curlHandle);
echo $response;
$response = array($response);
echo $response[0];
I get a json string that looks something like this:
[
{
"ID": "123",
"Description": "Champion Football Navy T-shirt",
"HighPrice": 16.99,
"LowPrice": 16.99,
"SalePrice": null,
"OnSale": false,
"URL": "http://www.mystore.com/itemDescription",
"ImageURL": "http://www.mystore.com/mainstore/045.jpg",
"LargeImageURL": "http://www.mystore.com/mainstore/045.jpg",
"ThumbnailImageURL": "http://www.mystore.com/mainstore/045.jpg",
"MiniImageURL": "http://www.mystore.com/mainstore/045.jpg",
"AffiliateID": ""
},
{
"ID": "23",
"Description": "Champion Football Navy T-shirt XL",
"HighPrice": 16.99,
"LowPrice": 16.99,
"SalePrice": null,
"OnSale": false,
"URL": "http://www.mystore.com/itemDescription",
"ImageURL": "http://www.mystore.com/mainstore/045.jpg",
"LargeImageURL": "http://www.mystore.com/mainstore/045.jpg",
"ThumbnailImageURL": "http://www.mystore.com/mainstore/045.jpg",
"MiniImageURL": "http://www.mystore.com/mainstore/045.jpg",
"AffiliateID": ""
}
]
However when I echo $response[0] I get the entire string. If I use json_decode or encode I get a string but with quotes around it. I can't figure out how to cast this dang thing so it operates as an array of objects that I can then iterate through. Thanks for any help in advance
Try this...
$itemURL = 'http://***.***.***/search?tag=Football&affiliate_id=&max_results=3';
$response = file_get_contents($itemURL);//curl_exec($curlHandle);
$response = json_decode($response);
You'll get an object like...
array(2) {
[0]=>
object(stdClass)#1 (12) {
["ID"]=>
string(3) "123"
["Description"]=>
string(30) "Champion Football Navy T-shirt"
["HighPrice"]=>
float(16.99)
["LowPrice"]=>
float(16.99)
["SalePrice"]=>
NULL
["OnSale"]=>
bool(false)
["URL"]=>
string(38) "http://www.mystore.com/itemDescription"
["ImageURL"]=>
string(40) "http://www.mystore.com/mainstore/045.jpg"
["LargeImageURL"]=>
string(40) "http://www.mystore.com/mainstore/045.jpg"
["ThumbnailImageURL"]=>
string(40) "http://www.mystore.com/mainstore/045.jpg"
["MiniImageURL"]=>
string(40) "http://www.mystore.com/mainstore/045.jpg"
["AffiliateID"]=>
string(0) ""
}
[1]=>
object(stdClass)#2 (12) {
["ID"]=>
string(2) "23"
["Description"]=>
string(33) "Champion Football Navy T-shirt XL"
["HighPrice"]=>
float(16.99)
["LowPrice"]=>
float(16.99)
["SalePrice"]=>
NULL
["OnSale"]=>
bool(false)
["URL"]=>
string(38) "http://www.mystore.com/itemDescription"
["ImageURL"]=>
string(40) "http://www.mystore.com/mainstore/045.jpg"
["LargeImageURL"]=>
string(40) "http://www.mystore.com/mainstore/045.jpg"
["ThumbnailImageURL"]=>
string(40) "http://www.mystore.com/mainstore/045.jpg"
["MiniImageURL"]=>
string(40) "http://www.mystore.com/mainstore/045.jpg"
["AffiliateID"]=>
string(0) ""
}
}
And then you can access your JSON objects using $response[0], $response[1], etc... Using the specific name of the field like $response[0]->AffiliateID for istance.
you need to call the property you are looking for
IE:
echo response[0].ID; //getting the 1st item in the response array then access the "ID" property of the json object.
The json response is a dynamic object that allows you to interact with all the properties as though you created the object from scratch.
The values inside the [{... and the ... }] are the object values.
so...
var json = '{"ID" : 1, "Prop1" : "Value1", Prop2 : "Value2" }';
can be parsed using jQuery's parseJSON method
var obj= jQuery.parseJSON(json);
echo obj.ID; //1
echo obj.Prop1; //Value
echo obj.Prop2; //Value2
When you have the [... and ...] around the { and } you know this object is an array and needs to be treated accordingly.
Hope this helps.
wm
if (mysql_num_rows($result) > 0) {
$response["events"] = array();
while ($row = mysql_fetch_array($result)) {
$tmparr = array();
$tmparr["uid"] = $row["uid"];
$tmparr["date"] = $row["date"];
$tmparr["hours"] = $row["hours"];
$tmparr["store_name"] = $row["store_name"];
$tmparr["event_information"] = $row["event_information"];
$tmparr["event_type"] = $row["event_type"];
$tmparr["Phone"] = $row["Phone"];
$tmparr["price"] = $row["price"];
$tmparr["address"] = $row["address"];
$tmparr["image_url"] = $row["image_url"];
$tmparr["created_at"] = $row["created_at"];
$tmparr["updated_at"] = $row["updated_at"];
array_push($response["events"], $tmparr);
}
$response["success"] = 1;
echo json_encode($response);
I can't understand what you are trying to do but This is the way that i use in order to return an array of rows of data from a sql query ($result). I hope this helps you
I am working on a script, that will use steam api, and i selected to use json for the response format.
So i have used var_dump with and without jason_decode() and it appears to be ok.
But can't manage to print it out, or echo it.
Script that gets the json data
<?php
$id = $_GET['SteamId'];
$get = file_get_contents("http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key=API_KEY_REMOVED_FOR_SECURITY&steamids=$id",true);
$data = json_decode($get);
//var_dump($data);
echo $data->realname;
?>
So, that i get using the var_dump with json_decode is this.
object(stdClass)#1 (1) { ["response"]=> object(stdClass)#2 (1) { ["players"]=> array(1) { [0]=> object(stdClass)#3 (15) { ["steamid"]=> string(17) "76561198053511970" ["communityvisibilitystate"]=> int(3) ["profilestate"]=> int(1) ["personaname"]=> string(9) "Undefined" ["lastlogoff"]=> int(1340978067) ["profileurl"]=> string(41) "http://steamcommunity.com/id/Heisteknikk/" ["avatar"]=> string(114) "http://media.steampowered.com/steamcommunity/public/images/avatars/5c/5c75278da69102d9c8290bccd1becbb4081954cd.jpg" ["avatarmedium"]=> string(121) "http://media.steampowered.com/steamcommunity/public/images/avatars/5c/5c75278da69102d9c8290bccd1becbb4081954cd_medium.jpg" ["avatarfull"]=> string(119) "http://media.steampowered.com/steamcommunity/public/images/avatars/5c/5c75278da69102d9c8290bccd1becbb4081954cd_full.jpg" ["personastate"]=> int(1) ["realname"]=> string(7) "Andreas" ["primaryclanid"]=> string(18) "103582791430704052" ["timecreated"]=> int(1322427688) ["loccountrycode"]=> string(2) "NO" ["locstatecode"]=> string(2) "09" } } } }
And the raw data from the json.
{
"response": {
"players": [
{
"steamid": "76561198053511970",
"communityvisibilitystate": 3,
"profilestate": 1,
"personaname": "Undefined",
"lastlogoff": 1340978067,
"profileurl": "http:\/\/steamcommunity.com\/id\/Heisteknikk\/",
"avatar": "http:\/\/media.steampowered.com\/steamcommunity\/public\/images\/avatars\/5c\/5c75278da69102d9c8290bccd1becbb4081954cd.jpg",
"avatarmedium": "http:\/\/media.steampowered.com\/steamcommunity\/public\/images\/avatars\/5c\/5c75278da69102d9c8290bccd1becbb4081954cd_medium.jpg",
"avatarfull": "http:\/\/media.steampowered.com\/steamcommunity\/public\/images\/avatars\/5c\/5c75278da69102d9c8290bccd1becbb4081954cd_full.jpg",
"personastate": 1,
"realname": "Andreas",
"primaryclanid": "103582791430704052",
"timecreated": 1322427688,
"loccountrycode": "NO",
"locstatecode": "09"
}
]
}
}
I've been searching around on google about printing the json using "echo $data->realname;".
So i don't know what i did wrong, so it canno't echo the data.
Intro
Hey there, this is a REALLY old question, but since there's no answer here.
You do have it right when it comes to decoding the JSON PHP has the built-in function json_decode which can easily decode the function for you:
$json = '{...}';
$obj = json_decode($json, [ASSOC_ARRAY = FALSE]);
The second Param you can set to bool for an associative array which would change mentions from:
$obj->response;
To
$obj['response'];
Response
Now you say you need the realname from the players, that would be as simple as getting it via the player's position in the array, or just looping through the array:
echo $obj->response->players[0]->realname; // Andreas
Or if you have multiple users:
for( $i = 0; $i < count($obj->response->players); $i++ ) {
echo $obj->response->players[$i]->realname;
}
Which would display all of the realname(s)