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
Related
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 2 years ago.
Improve this question
I have a json like this {"1":["3","5","6","2","4","1"],"2":[]} and I want to push a value inside the array in the key "2" so I want to do like this {"1":["3","5","6","2","4","1"],"2":["myvalue"]}.
I've tried many ways but no luck.
This is what I tried
/// json = {"1":["3","5","6","2","4","1"],"2":[]}
$arrayparole= $json["2"];
array_push($arrayparole,"myvalue");
$json = $json + array("2"=>$arrayparole);
$record = json_encode($json);
but doesn't work.
Can you help me?
The JSON you have is basically a string. Therefore you cannot access the JSON using the index like you did.
What you need to do is to convert the JSON string into Array first. After you have the array, only you are able to access the values using index/keys.
You can only push value into an array.
You cannot append array to a string like you did.
$json = $json + array("2"=>$arrayparole);
Following are example of converting the string into array and use array_push to insert new value.
$jsonstring = '{"1":["3","5","6","2","4","1"],"2":[]}';
// decode the JSON string into Array
$array = json_decode($jsonstring, true);
// once you have the array, you can now push your value
array_push($array[2],"myvalue");
// now you can convert back the array to json
echo json_encode($array);
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
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 4 years ago.
Improve this question
This is my first time working with json, just playing around with some data.
This is part of my json
Array
(
[DataSet] => Array
(
[Table] => Array
(
[0] => Array
(
[Driver] => John Doe
[Shift Date] => 2018-01-05T00:00:00-05:00
I want to be able to get all the [Driver] and [Shift Date] fields and put them into a table. It has 2 columns Driver and ShiftDate, not sure where I go from here.
After lots of googling I have come up with the solution, and I apologize if I didn't word my question right this is my first crack at this, but I figured posting the answer may help someone else trying to figure this out:
$str = file_get_contents('./cgapi.json');
$json = json_decode($str, true);
foreach($json['DataSet']['Table'] as $item) {
$stmt = $dbcon->prepare("INSERT INTO DriverData (DriverName, ShiftDate, Minutes, Stops, Gallons) VALUES (?,?,?,?,?)");
$stmt->bind_param("sssss", $item['Driver'], $item['Shift Date'], $item['Minutes'], $item['Stops'], $item['Gallons']);
$stmt->execute();
$stmt->close();
}
$drivers = array_column('Driver', $yourData);
$dates = array_column('Shift Date', $yourData);
Array column extracts all the values of the key provided as the first argument.
http://php.net/manual/en/function.array-column.php
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);