Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I have the following being sent to a PHP/Laravel endpoint which I am working on. I need to convert it to PHP array so I can iterate through the members but I can't seem to be able to do json_decode() on it
{
levels: [
{role_id:1, access_level_id:3},
{role_id:2, access_level_id:1},
{role_id:3, access_level_id:2}],
category_id: 3
}
On my backend I have my method as follows
public function myfunctionname (Request $request)
{
$levels = json_decode($request->levels);
}
I want to be able to iterate through the items in $request levels as a PHP array but $levels is returning as empty
I guess I am doing something wrong about this.
Please guide if you can
Thank you
Read this solution only if you are using javascript to generate the json:
When sending json via ajax you can turn it into a regular json string with JSON.stringify:
var v = {
levels: [
{role_id:1, access_level_id:3},
{role_id:2, access_level_id:1},
{role_id:3, access_level_id:2}],
category_id: 3
};
var j = JSON.stringify(v);
console.log(j);
{"levels":[{"role_id":1,"access_level_id":3},{"role_id":2,"access_level_id":1},{"role_id":3,"access_level_id":2}],"category_id":3}
... and you can decode this with json_decode(..., true) on PHP.
Your keys are not quoted properly, this is the format that json_decode expects, this is the reason why you are getting null. To iterate through the items it's better to use json_decode($jsonString, true); Note the second parameter set as true, this second parameter will return an array instead of an object of type \stdClass.
See the following example:
https://3v4l.org/GM5fR
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 28 days ago.
This post was edited and submitted for review 27 days ago and failed to reopen the post:
Original close reason(s) were not resolved
Improve this question
I'm receiving data from a webservice in this format - yes, the variable var visual is included:
var visual = {
"status": "ok",
"cached": "1",
"cache_time": "1674481162",
"photos": [{
"photo_id": "81517195",
"title": "title 1"
}, {
"photo_id": "79383391",
"title": "Title 2"
}]
}
See the response here. I guess it's not valid json - I seem to receive it as a string. How can I convert it into json so that I can iterate over each "photos" node with php?
You can use the php function json_decode. Even tough your code looks like it was written in javascript, if you had the same code as a PHP variable called as $visual (with it containing the string, as you mentioned), the solution would look something like this:
$visual = "..."; // the response in string format
$decodedJSON = json_decode($visual, true) // $decodedJSON will contain the provided json in an associative array (specified by the second param)
$firstPhoto = $decodedJSON["photos"][0]; // getting the first photo
You can find more information in the documentation.
EDIT: as #MerlinDenker mentioned above, if you get the var visual = ... with your response, then you just have to remove it from the beginning of your response (it can be done using substr() for example), and then pass it to the json_decode as a string.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
Can someone help me with this difficult array
In the web im find all cities and regions of Ukraine and im want to display this in select-option tag
I want to show separately regions and cities
This is link of json file
Also im saved this JSON file on my PC
This is my code of proccessing arrays
public function index()
{
$result = json_decode(file_get_contents('5.json'));
foreach ($result as $k => $v)
{
foreach ($v as $item)
{
dd($item);
}
}
return response()->json($item);
}
I think should format $result to array
$result = json_decode(json_encode($result), true);
Laravel provides a fluent wrapper for arrays. See Collections.
Initialize a collection by:
$result = json_decode(file_get_contents('5.json'));
$collection = collect($result);
Looking at your data, I don't know if this will perform well. I had experiences before where performance starts to become a problem, so please be wary of usage.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I have a MySQL database with a 'params' field containing Json encoded data. An example of the field contents is:
{"subcustom":{"slaveusers":["Jon Doe"]}}
How can I extract the name "Jon Doe" using Php?
Use json_decode to transform your json string into an object, if you know what you are looking for, do
<?php
$json = '{"subcustom":{"slaveusers":["Jon Doe"]}} ';
$obj = json_decode($json);
print_r($obj->subcustom->slaveusers[0]) ; // Jon Doe
?>
if you don't know the structure of your json, use a print_r or vardump to check the content
To do this as array you add the 'true' flag to json_decode():
$json = '{"subcustom":{"slaveusers":["Jon Doe"]}} ';
$json_array = json_decode($json, true);
print_r($json_array); // Array ([subcustom] => Array ([slaveusers] => Array ([0] => Jon Doe)))
Once you have an array you can follow the tree to get the element(s) you want:
echo $json_array['subcustom']['slaveusers'][0]; // Jon Doe
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
EDIT: I found my mistake thanks to the comments about decoding the JSON data.
I am a total rookie in PHP and couldn't find a suitable method to access Associative array.
I have this JSON data:
[{"Id":"1"},{"Id":"2"},{"Id":"3"},{"Id":"4"},{"Id":"5"},{"Id":"6"},{"Id":"7"},{"Id":"8"}]
I need to fire another MySQLi query in my PHP code which requires 1,2,3... from above data.
Implementing various solutions on this site gives me Array to String Conversion error.
Please Help.
You can simply use array_column amd implode as
$json = '[{"Id":"1"},{"Id":"2"},{"Id":"3"},{"Id":"4"},{"Id":"5"},{"Id":"6"},{"Id":"7"},{"Id":"8"}]';
$data = implode(',',array_column(json_decode($json,true),'Id'));
echo $data;//1,2,3,4,5,6,7,8
Explanation:
json_decode($json,true) will convert your json string into an array
array_column(json_decode($json,true),'Id') will returns the values from a single column of the array, identified by the column_key i.e Id over here
implode will Join array elements with a glue string i.e ,.
convert json data to associative array:
<?php
$json = '[{"Id":"1"},{"Id":"2"},{"Id":"3"},{"Id":"4"},{"Id":"5"},{"Id":"6"},{"Id":"7"},{"Id":"8"}]';
$data = json_decode($json,true);
echo "<pre>";
print_r($data);
echo "<pre>";
?>
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
My variable which retrieve from database is:
$MyVariable="1=>'raju',2=>'rana',3=>'keya',4=>'muaz',5=>'',6=>'Asif'";
My array will be:
$MyArray=array($MyVariable);
Now I want to print a value using a key. Like:
echo $MyArray[2];
My output should be:
rana
But output is nothing!
eval() has security implications, but that's how this string of partial crap is turned into an actual array:
eval('$MyArray = array('.$MyVariable.');');
print_r($MyArray);
You should really store each value as a related row in another table instead of array data.
Your variable $myVariable is a string consisting of array keys.
If you were to write it as an array, it would work without problems:
$myvariable = array(
1 => 'raju',
2 => 'rana',
3 => 'keya'
// More entries
);
If this is the output of a function, you may want to make that function output JSON instead, as that is parseable to an array with just one json_decode call.
If you still want to parse this, you'll have to do some more advanced string parsing:
$data = array();
$bits = preg_match_callback("/(\d+)=>'(.*?)'(\,)?/", function($matches) use ($data){
$data[$matches[1]] = $matches[2];
}, $MyVariable);