Decode JSON post data - php

My php file receives a post from ajax call. The string received by the php file is as follows :
array(1) { ["userid"]=> string(21) "assssssss,camo,castor" }
I am trying unsuccessfully to decode this string then loop through the values in the array. I have tried the following :
$myarray =json_decode($_POST["userid"],true);
foreach ($myarray as $value) {
//do something with value
}
I am not sure whether the decode is the issue or my syntax to loop through the PHP array.

The POST data you'd want to manipulate is stored in $_POST['userid]
In case you're trying to access this comma separated user ids, you need to convert this to an array first using explode(). And then loop through these id's.
if (isset($_POST)) {
$user_ids = $_POST['userid']; // assssssss,camo,castor
$user_id_arr = explode(',', $user_ids); // Converts string to array Array (0 => assssssss, 1 => camo, 2 => castor)
foreach ($user_id_arr as $user_id) {
//Statements
}
}

$_POST is an associative array of variables passed to the current script via the HTTP POST method when using application/x-www-form-urlencoded or multipart/form-data as the HTTP Content-Type in the request. So when you decode with json_decode that will decode JSON string to Object/Array.
But in your scenario you have not passed JSON String to $_POST so it not looks decoding.

The string you have passed into your $_POST is not JSON, so json_decode will not work on some random comma seperated values.
You can either pass in real JSON, or just use the explode method of splitting these values:
// explode example
$users = "assssssss,camo,castor";
$usersarray = explode(",", $users);

Related

read jquery array in php

i am trying to retrieve the value of array via post in php script.
var data = [];
table.rows({ selected: true }).every(function(index){
// Get and store row ID
data.push(this.data()[0]); //create a 1 dimensional array
});
//send data via ajax
$.ajax({
url: '/...../...',
type: 'POST',
data: {userid:data},
dataType: 'json',
In my PHP script so far I am unable to decode the array. Have tried many ways
$myArray = $_REQUEST['userid'];
foreach ($arr as $value) {
$userid= $value; //for now just trying to read single item
}
I have tried print_r($myArray ); this sucessfully prints array contents to screen.
I am trying to retrieve the values for processing! Kindly point me in the right direction
I don't think that PHP would recognise the array that you've called "data" as being an array. Couldn't you turn the data from your table rows into values in a JavaScript object, encode it as a JSON string, then post that to your PHP script and use json_decode($_POST["userid"]) on the PHP end to convert it into a PHP array.
The object you are posting to PHP isn't in particular a jQuery object. Instead it is an JSON object or rather a JSON string. I guess you can't read that object the way you would read an regular array in PHP.
You might want to try to decode the string with json_decode(). With true as an function argument, it will return an php array as suggested in this stackoverflow answer https://stackoverflow.com/a/6964549/6710876
$phpArray = json_decode($myArray, true);
Documentation of json_decode(): http://php.net/manual/en/function.json-decode.php
simply use:
echo json_encode($myArray);
You're foreach is looping $arr, which doesn't exist. Your array is being set to $myArray, so use that in your for.
$myArray = $_REQUEST['userid'];
foreach ($myArray as $value) {
$userid= $value; //for now just trying to read single item
}
I believe you should also be able to find your values in $_POST
According to your var_dump :
array(1) { ["userid"]=> string(21) "assssssss,camo,castor" }
and if we assume "assssssss,camo,castor" are 3 different usernames.
You should use this:
$userids=explode(",",$myArray->userid);
foreach($userids as $userid){
// use $userid
}

Query and decode json form mysql database

I have this JSON encoded code in my mysql database:
{"Suggestion":{"Title":"Casinos","Text":"maybe it will be good if its there casinos "},"ID":6,"VoteNo":[],"Status":"Voting","Player":{"SteamID":"STEAM_0:1:36988062","Name":"Pepi"},"Approved":{"Name":"Nido Johnson","Is":true,"SteamID":"STEAM_0:0:47457253"},"VoteYes":{"1":"STEAM_0:0:56939043","2":"STEAM_0:0:55948188","3":"STEAM_0:1:25856984","4":"STEAM_0:1:40894071"}}
And i want to query and decode it to echo it at my website.
You have to use a php "json_decode()" function to decode a json encoded data.
Basically json_decode() function converts JSON data to a PHP array.
Syntax: json_decode( data, dataTypeBoolean, depth, options )
data : - The json data that you want to decode in PHP.
dataTypeBoolean(Optional) :- boolean that makes the function return a PHP Associative Array if set to "true", or return a PHP stdClass object if you omit this parameter or set it to "false". Both data types can be accessed like an array and use array based PHP loops for parsing.
depth :- Optional recursion limit. Use an integer as the value for this parameter.
options :- Optional JSON_BIGINT_AS_STRING parameter.
Now Comes to your Code
$json_string = '{"Suggestion":{"Title":"Casinos","Text":"maybe it will be good if its there casinos "},"ID":6,"VoteNo":[],"Status":"Voting","Player":{"SteamID":"STEAM_0:1:36988062","Name":"Pepi"},"Approved":{"Name":"Nido Johnson","Is":true,"SteamID":"STEAM_0:0:47457253"},"VoteYes":{"1":"STEAM_0:0:56939043","2":"STEAM_0:0:55948188","3":"STEAM_0:1:25856984","4":"STEAM_0:1:40894071"}}';
Assign a valid json data to a variable $json_string within single quot's ('') as
json string already have double quots.
// here i am decoding a json string by using a php 'json_decode' function, as mentioned above & passing a true parameter to get a PHP associative array otherwise it will bydefault return a PHP std class objecy array.
/ just can check here your encoded array data.
// echo '<pre>';
// print_r($json_decoded_data);
// loop to extract data from an array
foreach ($json_decoded_data as $key => $value) {
echo "$key <br/>";
foreach($value as $k=>$data)
{
echo "$k | $data <br/>";
}
}

Get the value for key in json array in php

How to get the corresponding value for key associated
[{"name":"challenge","properties":[{"name":"mobileNo","value":"aa"},{"name":"challengeT","value":"1Day"},{"name":"emailId","value":"ff#gmail.com"},{"name":"deviceId","value":"9500e297-081b-4f97-93b7-dafddc55db31"}]},{"name":"challenge","properties":[{"name":"emailId","value":"a#b.com"},{"name":"mobileNo","value":"345345"},{"name":"deviceId","value":"435435dfgdfg"}]}]
Your Json is valid. You can validate at following
website: http://jsonlint.com/
You have to use a php "json_decode()" function to decode a json encoded data.
Basically json_decode() function converts JSON data to a PHP array.
Syntax: json_decode( data, dataTypeBoolean, depth, options )
data : - The json data that you want to decode in PHP.
dataTypeBoolean(Optional) :- boolean that makes the function return a PHP Associative Array if set to "true", or return a PHP stdClass object if you omit this parameter or set it to "false". Both data types can be accessed like an array and use array based PHP loops for parsing.
depth :- Optional recursion limit. Use an integer as the value for this parameter.
options :- Optional JSON_BIGINT_AS_STRING parameter.
Now Comes to your Code
$json_string = '[{"name":"challenge","properties":[{"name":"mobileNo","value":"aa"},{"name":"challengeT","value":"1Day"},{"name":"emailId","value":"ff#gmail.com"},{"name":"deviceId","value":"9500e297-081b-4f97-93b7-dafddc55db31"}]},{"name":"challenge","properties":[{"name":"emailId","value":"a#b.com"},{"name":"mobileNo","value":"345345"},{"name":"deviceId","value":"435435dfgdfg"}]}]' ;
Assign a valid json data to a variable $json_string within single quot's ('') as
json string already have double quots.
// here i am decoding a json string by using a php 'json_decode' function, as mentioned above & passing a true parameter to get a PHP associative array otherwise it will bydefault return a PHP std class objecy array.
$json_decoded_data = json_decode($json_string, true);
// just can check here your encoded array data.
// echo '<pre>';
// print_r($json_decoded_data);
// loop to extract data from an array
foreach ($json_decoded_data as $key => $value) {
echo "$key <br/>";
foreach ($value as $key2 => $value2) {
echo "$key2 = $value2 <br />";
}
}
Output :
0
name = challenge
properties = Array
1
name = challenge
properties = Array

Get JSON data type from associative array in PHP

Evening everyone!
So, I have with me a JSON string...
{"username":"87db3983285d395ca0af9f","password":"f4f0bb1533ef5034ce6b0a8a7c49a43b","email":"xxx#gmail.com","hnum":3,"splicenum":22,"reg_ip":"71.126.122.217","reg_date":1364175245,"cur_ip":"71.126.122.217","ip_array":["71.126.122.217"],"logins":[],"about":""}
And I decode this string into an associative array in PHP using json_decode().
What I'm doing is trying to make 1 single function for querying a JSON object that has been converted to an associative array in PHP. For this function, I am now working on editing/updating fields.
Example:
json_edit(array(
"set"=>array(
"email"=>"yyy#yahoo.com"
)
));
The key "set" means setting the value of a string or boolean.
Another key would be "push" to append to an array, or "delete" to delete a string or an array.
What I'm wondering is, how can I get the data type of the current array part in PHP?
Meaning, how can I get PHP to say, "OK, the field 'username' is a string, and 'ip_array' is an array"?
I don't want to be able to "set" a string value to what is SUPPOSED to be just a boolean, or, an array.
Is there any way to get the JSON data types in PHP?
Thanks so much in advance.
What about gettype(). Gettype() will return the data type of any variable. http://php.net/manual/en/function.gettype.php
I would use something like this;
<?php
function json_edit($json, $changes = array()){
$decoded = json_decode($json);
foreach($changes as $action => $data){
swith($action){
case 'SET':
foreach($data as $key => $value){
$decoded[$key] = $value;
}
break;
case 'DELETE' :
break;
default;
}
}
return json_encode($decoded);
}
?>

How to get individual fields from JSON in PHP

My JSON looks like this. How do I get a specific field, e.g. "title" or "url"?
{
"status":1,
"list":
{
"204216523":
{"item_id":"204216523",
"title":"title1",
"url":"url1",
},
"203886655":
{"item_id":"203886655",
"title":"titl2",
"url":"url2",
}
},"since":1344188496,
"complete":1
}
I know $result = json_decode($input, true); should be used to get parsable data in $result, but how do I get individual fields out of $result? I need to run through all the members (2 in this case) and get a field out of it.
json_decode() converts JSON data into an associative array. So to get title & url out of your data,
foreach ($result['list'] as $key => $value) {
echo $value['title'].','.$value['url'];
}
echo $result['list']['204216523']['item_id']; // prints 204216523
json_decode() translates your JSON data into an array. Treat it as an associative array because that's what it is.

Categories