PHP Arrays to JSON data - php

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

Related

Adding element data with Array_push to JSON file

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.

How to filter and restructure json data with php?

I couldn't find an answer, so I decided to ask.
I get this response from an API:
[
{
"seasonNumber":1,
"numWins":1,
"numHighBracket":2,
"numLowBracket":2,
"seasonXp":111,
"seasonLevel":5,
"bookXp":0,
"bookLevel":1,
"purchasedVIP":false
},
{
"seasonNumber":2,
"numWins":1,
"numHighBracket":21,
"numLowBracket":31,
"seasonXp":1651,
"seasonLevel":25,
"bookXp":9,
"bookLevel":11,
"purchasedVIP":false
},
{
"seasonNumber":3,
"numWins":9,
"numHighBracket":57,
"numLowBracket":127,
"seasonXp":4659,
"seasonLevel":68,
"bookXp":0,
"bookLevel":100,
"purchasedVIP":true
},
{
"seasonNumber":4,
"numWins":8,
"numHighBracket":19,
"numLowBracket":36,
"seasonXp":274,
"seasonLevel":33,
"bookXp":7,
"bookLevel":35,
"purchasedVIP":true
}
]
I am trying to change the json data to this:
{
"seasons":
[
{
"season":1,
"battle_pass":false
},
{
"season":2,
"battle_pass":false
},
{
"season":3,
"battle_pass":true
},
{
"season":4,
"battle_pass":true
}
]
}
In my current code I am using regex like this:
preg_match_all("/(?:\{\"seasonNumber\"\:(\w)|purchasedVIP\"\:(\w+))/", $response, $seasons);
echo '{"seasons":'.json_encode($seasons, JSON_FORCE_OBJECT, JSON_PRETTY_PRINT).'}';
It's basically putting everything in a separate array but that's not what I want.
Decode the json, restructure the data, re-encode.
Code: (Demo)
// your $json =
foreach (json_decode($json) as $set) {
$array[] = ["season" => $set->seasonNumber, "battle_pass" => $set->purchasedVIP];
}
echo json_encode(["seasons" => $array]);
Output:
{"seasons":[{"season":1,"battle_pass":false},{"season":2,"battle_pass":false},{"season":3,"battle_pass":true},{"season":4,"battle_pass":true}]}
p.s. if you want to force objects and pretty print, separate those flags with a pipe (|). https://3v4l.org/qsPb0

merge Array of objects into array with unique object

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);

PHP function to validate array elements for n level

I have tried out with the google and tried myself to get done for the below functionality. I need a function that will validate each array element whether it is scalar or not. So i wrote a simple function that will iterate each element of the array and checks for scalar or not.
But the real requirement, the array could be a multi dimentional array. So i have modified the array and called the function recursively as below, But it will not go-through all elements in the array.
function validate_scalar($params)
{
foreach ($params as $key => $arg)
{
if (is_array($arg))
{
validate_scalar($arg);
}
else
{
if (!is_scalar($arg))
{
// throwing an exception here if not scalar.
}
}
}
return true;
}
Is there any method to achieve this functionality? Please help me on this.
array_walk_recursive
You could use something like this:
<?php
$array = array(
'kalle' => 'asdf',
'anka' => array(
123,
54324,
new stdClass()
)
);
array_walk_recursive($array, function ($item, $key) {
if (!is_scalar($item)) {
echo $key . " => : Is not scalar\n";
return false;
}
echo $key . " => : Is scalar\n";
return true;
});
array_walk_recursive ignores values that are arrays
output:
kalle => : Is scalar
0 => : Is scalar
1 => : Is scalar
2 => : Is not scalar

decode mysql query before returning it to view

I'm running a query to mysql that returns encrypted data. I'd like, if possible, to decode the results before sending it to the view. It seems like better form to handle the decoding in the controller (or even the model) rather than inside the view.
I can't seem to wrap my head around how to do it, though.
I was thinking I could iterate through the object, decodode it, and push it to another array that would be sent to the view. Problem with this is I won't know (and need to keep) the indexes of the query.
So the query might return something like:
[id] => 742
[client_id] => 000105
[last] => dNXcw6mQPaGQ4rXfgIGJMq1pZ1dYAim0
[first] => dDF7VoO37qdtYoYKfp1ena5mjBXXU0K3dDlcq1ssSvCgpOx75y0A==
[middle] =>iXy6OWa48kCamViDZFv++K6okIkalC0am3OMPcBwK8sA==
[phone] => eRY3zBhAw2H8tKE
Any ideas?
Ended up with:
function name(){
$data['e_key']=$this->e_key;
$clid = $this->uri->segment(3);
$name = $this->Clients_model->getNameData('*','client_id='.$clid,'');
$nameArray= array();
foreach ($name->result() as $row){
$x = $row;
$keys = array('id','client_id');
$unenc = array();
foreach ($x as $key=>$value){
if(! in_array($key, $keys)){
$unenc[$key]=$this->encrypt->decode($value,$this->e_key);
}else{
$unenc[$key]=$value;
}
}
array_push($nameArray,$unenc);
}
$data['name'] = $nameArray;
$this->load->view('names/name_view',$data);
}
Assuming you know how to decrypt the data, it's but a matter of iterating over the object, decrypting the encrypted fields.
If $YOUR_OBJECT is your object and your function for decryption is decode() then the following code should do the trick.
// The keys corresponding to the encrypted fields
$encoded = array('last', 'first', 'middle', 'phone');
$decoded = array();
foreach($YOUR_OBJECT as $key => $value)
{
if (in_array($key, $encoded))
{
$decoded[$key] = decode($value);
}
}
if it's a particular index, you could decode it like
$result['last'] = base64_decode($result['last']);
or in the model, use mutators and accessors:
public function setUp() {
$this->setTableName('tablename');
$this->actAs('Timestampable');
$this->hasMutator('last', '_encode64');
$this->hasAccessor('last', '_decode64');
}
protected function _encode($value) {
$this->_set('last',base64_encode($value));
}
protected function _decode($value) {
return base64_decode($value); // not sure on this one - might have to
// return $this->set('last', base64_decode($value));
}

Categories