I need to iterate some JSON formatted data into loop using PHP. My JSON data is below:
{
"question1":{
"ques":"questin1",
"optional":[
{
"opt":"option1"
},
{
"opt":"option2"
}
]
},
"question2":{
"ques":"questin2",
"optional":[
{
"opt":"option1"
},
{
"opt":"option2"
}
]
}
}
I need to run the loop so that the result data will come in above format using PHP.
Convert the php object to json object using json_encode
// convert object => json
$json = json_encode($myObject);
This might helpful: https://stackoverflow.com/a/9858457/6285410
What you showed us is a Possible JSON Data. In this Format, we can do nothing with it in PHP except by decoding back into Native PHP Object. Once that is done, You can access all the Properties of the Object like you do with normal PHP Object like $objData->questin1. Here's what is meant with the above statements:
<?php
$strJson = '{
"question1":{
"ques":"questin1",
"optional":[
{
"opt":"option1"
},
{
"opt":"option2"
}
]
},
"question2":{
"ques":"questin2",
"optional":[
{
"opt":"option1"
},
{
"opt":"option2"
}
]
}
}';
$objData = json_decode($strJson);
var_dump($objData);
// NOW, TO GET AT EACH OF THE PROPERTIES OF THE OBJECT IS EASY...
// ACCESS THE question1 OR question2
$q1 = $objData->question1;
$q2 = $objData->question2;
// ACCESS THE que WITHIN question 1 OR question2
$k1 = $objData->question1->ques; // EQUIVALENT TO: $q1->ques
$k2 = $objData->question2->ques; // EQUIVALENT TO: $q2->ques
// ACCESS THE optional ARRAY INSIDE OF question 1 OR question2
$opt1 = $objData->question1->optional; // EQUIVALENT TO: $q1->optional
$opt2 = $objData->question2->optional; // EQUIVALENT TO: $q2->optional
var_dump($q1, $q2, $k1, $k2, $opt1, $opt2);
?>
Related
Need to insert the object in the entries array using array_push method of php where the value for test_view_id will be coming from another array. Can anyone please tell the syntax to do so.
$testViewId = array(12,13,14);
sample object
{
"miscResourceProperties":{
"test_view_id":12
}
}
Expected Output
$data = {
"eventStartTime":1656863552,
"entries":[
{
"miscResourceProperties":{
"test_view_id":12
}
},
{
"miscResourceProperties":{
"test_view_id":13
}
},
{
"miscResourceProperties":{
"test_view_id":14
}
}
]
}
I have a array of various object, but I need turn this objects into unique object. Below I share my code.
$result = [];
$idiomas = Idioma::all()->toArray();
foreach ($idiomas as $lang) {
$result[] = [
$lang['palavra_chave'] => $lang[$id]
];
}
return response()->json($result);
reponse
[
{ "INICIAL": "Inicial"},{ "RELATORIOS": "Relatórios"},{ "FUNCIONARIO": "Funcionário"},{ "DATA": "Data"},{ "ANEXAR_IMAGEM": "Anexar imagem"},{ "DISCIPLINA": "Disciplina"}
]
But I need transform this objects into one, like this
[
{
"INICIAL": "Inicial",
"RELATORIOS": "Relatórios",
"FUNCIONARIO": "Funcionário",
"DATA": "Data",
"ANEXAR_IMAGEM": "Anexar imagem",
"DISCIPLINA": "Disciplina"
}
]
anyone can help me?
$idiomas = Idioma::all()->toArray();
if (count($idiomas)) {
//$result = new stdClass; # wouldn't work without base namespace
$result = new \stdClass;
foreach ($idiomas as $lang) {
$result->{$lang['palavra_chave']} = $lang[$id];
}
return response()->json([$result]);
}
// otherwise
Edit: #Tpojka's answer definitely looks more appropriate. Use the following one only if you can't change the way you retrieve data initially (I'm not familiar enough with Laravel).
The following should work:
// Take your initial JSON
$input = <<<JSON
[
{ "INICIAL": "Inicial"},{ "RELATORIOS": "Relatórios"},{ "FUNCIONARIO": "Funcionário"},{ "DATA": "Data"},{ "ANEXAR_IMAGEM": "Anexar imagem"},{ "DISCIPLINA": "Disciplina"}
]
JSON;
// Transform it into a PHP array
$input_as_array = json_decode($input);
// Reduce it into an associative array
$associative_array = array_reduce($input_as_array, function($associative_array, $item) {
return $associative_array += (array)$item;
}, []);
// Encode it back into JSON, as an array
$result = json_encode([$associative_array], JSON_PRETTY_PRINT);
Setup
I have retrieved a JSON string from a URL using 'file_get_contents' and have subsequently decoded it using `json_decode'
$search_URL="http://abcdefg.com"
$json = file_get_contents($search_URL);
$obj = json_decode($json, true);
The JSON represents an Apache Solr search response:
{
"responseHeader":{
"status":0,
"QTime":3,
"params":{
"q":"zzzzzzz",
"wt":"json"
}
},
"response":{
"numFound":20690,
"start":0,
"docs":[
{
"title":"yyyyy-y-y-yyyyy-yy-y",
"author":"author 1, author 2, author 3",
"url":"https://yyyyy.com",
"id":yyyy,
"_version_":yyyyy
},
{
"title":"xxxx-x-x-xxxx-xxxx",
"author":"author 1, author 2",
"url":"https://xxxxx.com",
"id":xxxxx,
"_version_":xxxxxx
},
]
}
}
I basically need to grab each author field in the docs[] array, split it by commas to get a new array
$author_array = explode(", ", $author);
I then need to call another web service with these author names that will return JSON. I would love to simply plug this JSON in to my existing JSON and send it all back
Question
I need to modify my JSON so that each doc contains this new JSON object. How can I do this?
{
"title":"xxxx-x-x-xxxx-xxxx",
"author":"author 1, author 2",
"url":"https://xxxxx.com",
"id":xxxxx,
"_version_":xxxxxx,
"authors":[
{
"name": "author1",
"id": "143"
},
{
"name": "author2",
"id": "72"
}
]
}
My Attempt
I have tried a simpler version of this where I simply have an array of author names
{
"title":"xxxx-x-x-xxxx-xxxx",
"author":"author 1, author 2",
"url":"https://xxxxx.com",
"id":xxxxx,
"_version_":xxxxxx,
"authors":[
"author1",
"author2"
]
}
I tried the following:
$response = $obj['response'];
$docs = $response['docs'];
foreach($docs as &$doc) {
$author = $doc['author'];
$authors_array = explode(" ,", $author);
$doc['authors'] = $authors_array;
}
This has ultimately failed as the new array is not appended.
Explode the author string, call the API on each element, make an array of all these results, and put it back into the object.
I use a reference below in foreach so it can modify the document element directly.
foreach ($obj['response']['docs'] AS &$doc) {
$author_names = explode(',', $doc['author']);
$author_array = array_map('author_api', $author_names);
$doc['authors'] = $author_array;
}
for($i=0;$i<count($storetag);$i++){
$user=mysqli_query($con,"select user_id,profile_image_url from Wheel_User where user_id='$storetag[$i]'");
if(mysqli_num_rows($user)==0){
//For failure status if session id is wrong.
//http_response_code(404);
echo json_encode(array("status"=>"404","error"=>"Sorry, post id does not exists.".die()));
}
else{
$json_responce1=array();
while ($row = $user->fetch_array()){
$row_array['user_id'][$i]=explode(',',$row['user_id']);
$row_array['profile_image_url'[$i]=$row['profile_image_url'];
}
}
}
array_push($json_responce1,$row_array);
echo str_replace('\/','/', json_encode(array($json_responce1)));
It returns the following JSON
{
user_id: [3]
"1234",
"31332",
"12412"
profile_image_url: [3]
"localhost/1234.com",
"localhost/2345.com",
"localhost/3456.com"
}
but i want the json format like this
"user_id":[
{
"id":"1234",
"url":"localhost/1234.com"
},
{
"id":"1234",
"url":"localhost/1234.com"
},
{
"id":"1234",
"url":"localhost/1234.com"
}
]
You want to organise your array slightly different.
Try this
$row_array['user_id'][$i]['id']=explode(',',$row['user_id']);
$row_array['user_id'][$i]['url']=$row['profile_image_url'];
Everything should be within user_id and then by putting the $i before $id and $url, you will be grouping them as required.
I have this jsone that I need to convert in three different objects.
in some php. I know that i have to use json_decode but I only decode the first object , the others 2 object don't.
{
"recorrido":[
{
"lon":"-60.67216873168769",
"lat":"-32.9230105876913",
"date":"13/10/24-12:22:32",
"globaltime":"00:09",
"globalkm":0.0,
"speed":2.11,
"altitude":-32.9230105876913,
"groupId3":0,
"id":1,
"color":0,
"auxInt":0,
"groupId2":0,
"provider":1,
"groupId1":0,
"workoutid":1
},
{
"lon":"-60.67216873168769",
"lat":"-32.9230105876913",
"date":"13/10/24-12:22:35",
"globaltime":"00:12",
"globalkm":0.0,
"speed":2.11,
"altitude":-32.9230105876913,
"groupId3":0,
"id":2,
"color":0,
"auxInt":0,
"groupId2":0,
"provider":1,
"groupId1":0,
"workoutid":1
}
],
"user":{
"asunto":"",
"userId":1
},
"Itemout":{
"uploaded":"false",
"isSelected":false,
"id":1,
}
}
what do you sugest? the script must be in php. the object "recorrido" is a multiple array object.
wthout testing it, try somrting like this:
$tempArray = (array)$recorrido; // or how you cal your json object
foreach ($tempArray as $tempJson)
{
$myArray = json_decode($tempJson);
print_r($myArray);
}
You can use hardcode method if you have static json structure:
Show below
$result = json_decode($json);
$recorrido = $result->recorrido;
// And so on
In another way there is a workaround with arrays.
list($arr1, $arr2, $arr3) = json_decode($json, true);
This solution will make you three arrays of data from json.