I want to add data to existing JSON file
JSON:
{
"s1":[
{
"bID":"q4a4xs",
"bName":"Package1",
"bStep":"slast"
},
{
"bID":"q4a4xs",
"bName":"Package2",
"bStep":"s2"
}
],
"s2":[
{
"bID":"q4a4xs",
"bName":"Package15",
"bStep":"slast"
}
]
}
I want to create data for s3
What I did?
$newdata = ['bID' => 'O4bt2xs','bName' => 'Package91','bStep' => 's1'];
$newBox = 's3';
$encDexJSON = json_decode($json);
array_push($encDexJSON->{$newBox}->{$newdata}, $newdata);
Print:
{
"s1":[
{
"bID":"q4a4xs",
"bName":"Package1",
"bStep":"slast"
},
{
"bID":"q4a4xs",
"bName":"Package2",
"bStep":"s2"
}
],
"s2":[
{
"bID":"q4a4xs",
"bName":"Package15",
"bStep":"slast"
}
],
"w3":{
"Array":null
}
}
Where is the problem?
To be fair, the code you provided along with the given data wouldn't even give that result. However, it's obvious that you are doing a great number of things wrong here.
For starter's you're trying to call an array on object property, which makes no sense $encDexJSON->{$newBox}->{$newdata}. That literally translates to $encDexJSON->s3->['bID' => 'O4bt2xs','bName' => 'Package91','bStep' => 's1'] which obviously makes no sense at all.
Furthermore, array_push does not do what you want here. array_push is for arrays. What you want to do is simply assign a value to a specific object property. So just do so.
$encDexJSON->$newBox = [$newdata];
Now if you wanted to simply push new objects into that array...
$encDexJSON->$newBox[] = $newdata; // this pushes value onto end of array
The array_push equivalent would be...
$encDexJSON->$newBox = [];
array_push($encDexJSON->$newBox, $newdata); // same result as above
The use of array_push tends to get in the way. It's usually cleaner just to stick to the syntax above.
Related
I'm struggling to find a way to convert my object to the correct format.
I want to replace a function that we currently use on generating detailed array, as you can see below everything is static.
private function departmentArray($content=[])
{
return [ static::$A_DEPT_ID => $content
, static::$O_DEPT_ID => $content
];
}
A sample result when that runs is this
{"3":{"complete":0,"incomplete":0},"5":{"complete":0,"incomplete":0}}
I converted the method
private function departmentArray($content=[])
{
$depts = d::getAllMainDepartment();
$dept_array = [];
foreach ($depts as $dept) {
$dept_array[] = array($dept->id => $content);
}
return $dept_array;
}
The resulting format looks like this
[{"3":{"complete":0,"incomplete":0}},{"5":{"complete":0,"incomplete":0}}]
How can I maintain the same format on the first version of code?
You don't push into an associative array, you use the new key as an index.
$dept_array[$dept->id] = $content;
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);
I have arrays that looks like this:
Array ( [multi_YTnsPrfuB832.jpg] => gray [multi_hUORaTux1bI.jpg] => episode [multi_Ijtxz4U0iaq_.jpg] => fidgetq [multi_m0QWCyfVjDKh.jpg] => fidget2 )
the data inside the bracket is a URL and the value is the name. I want to encode this to be a json data to be something like this:
{ "offers":
{
"url":multi_YTnsPrfuB832.jpg,
"name":"gray"
},
{
"url":multi_hUORaTux1bI.jpg,
"name":"episode"
},
{
"url":multi_Ijtxz4U0iaq_.jpg,
"name":"fidgetq"
},
{
"url":multi_m0QWCyfVjDKh.jpg,
"name":"fidget2"
}
}
I'm fairly new to json so if someone has an idea how to implement this using php. Thanks!
To reformat your array all you need to do is iterate it and push to a new array in the format you are looking for. The json_encode function will turn an array into a JSON formatted string.
$array = /*your array*/;
$offers = [];
foreach ($array as $key => $value) {
$offers[] = ['url' => $key, 'name' => $value,];
}
$json = json_encode(['offers' => $offers,]);
echo $json;
yes, you can using json_encode($myArray)
You can use php function like this
echo json_encode($array);
and more click here
I am using the RPC service of ApiGilty to return some data. I would like to double check whether or not this is the correct way of formatting and returning the data as I am not 100% sure of the correct process.
EDIT: To clarify
The data is being built from a number of entities:
main
main_extra
main_data
main_data_days
main_data_tiers
Is there a way to hit main and get all the sub entities? Currently I am building my data from scratch and returning an array.
My RPC Controller is as follows:
use My\Data\Controller\DataInterface;
use Zend\Mvc\Controller\AbstractActionController;
use ZF\ContentNegotiation\ViewModel;
class MyDataController extends AbstractActionController
{
const GENERAL_ERROR = 'api.rpc.my-data.my-data-controller';
public function __construct(
MyDataInterface $myData
)
{
$this->myData = $myData;
}
public function myDataAction()
{
$my_id = (int) $this->params()->fromRoute('my_id', 0);
if ($my_id == 0)
{
$data = $this->myData->getMyData();
} else
{
$data = $this->myData->getMyData($my_id);
}
$result = new ViewModel(array(
'data' => $data
));
return $result;
}
}
Now to create the data I am doing something like this:
public function getMyData( $my_id = null )
{
$returnArray = [];
$array1 = [
'key_1' => [1,2,3,4],
'key_2' => '123',
'key_3' => ['a','b','c']
];
$array2 = [
'key_1' => [1,2,3,4,5,6,7,8],
'key_2' => '123456',
'key_3' => ['a','b','c','d']
];
if ($my_id == 1) {
$array3 = ['some','or','other'];
} else {$array3 = []; }
$final_array = [
'data1' => $array1,
'data2' => $array2,
'data3' => $array3
];
$returnArray['data'] = $final_array;
$returnArray['success'] = 'true';
$returnArray['reason'] = '';
return $returnArray;
}
When checking with postman, I get the following:
Now since I have nothing to reference this against, my question is simply. Have I gone about this in the correct way and is this how the return code should be formatted?
Thanks!
Right now the Hal plugin is not used to render your result? You are responding a custom json object. Is this really what you want?
The response you currently return is not formatted according to HAL specifications. A proper HAL response should hold at least a _links key with a self href. It would be wrong to return this result with Content-Type headers set to application/hal+json. You should use application/json instead.
Here you can find documentation on how to respond HAL from an RPC-contoller.
I am not sure what you want to achieve but maybe you can be a bit more specific in your question so others can help out...
Doesn't look too bad, perhaps adhere to a standard such as jsend http://labs.omniti.com/labs/jsend or you could use hal-json, matthew weier o'phinney has a good blog post on this https://mwop.net/blog/2014-03-26-apigility-rpc-with-hal.html
Also you don't need to return a view model as you can just return an array and apigility will return JSON. You could also write a jsendViewModel if you go down that route.
Not exactly an answer but hope this helps you!
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.