What is the best and fastest approach to do a string search and replace from a certain JSON value if it has lets say more than 100 strings to search in and each string needs its own unique replacement?
Is it better to create a php subclass with preg_replace using arrays and then import this into another PHP file where the JSON gets parsed?
My PHP knowledge is not that great and would appriciate if someone can guide me through this with some examples.
Here is my JSON code:
<?php
header('Content-Type: application/json');
$licensePlate = $_GET['kenteken'];
$json = file_get_contents('https://opendata.rdw.nl/resource/m9d7-ebf2.json?$q='.$licensePlate.'');
$array = json_decode($json);
if(count($array,1)==0) {
$data = ['resource' => ['code' => '404']];
echo json_encode($data);
return;
}
$item = array();
foreach ($array as $value) {
$item['code'] = '200';
$item['Aantalcilinders']=$value->aantal_cilinders;
$item['Aantalzitplaatsen']=$value->aantal_zitplaatsen;
$item['BPM']=$value->bruto_bpm;
$item['Cilinderinhoud']=$value->cilinderinhoud;
$item['Datumaanvangtenaamstelling']=$value->datum_tenaamstelling;
$item['DatumeersteafgifteNederland']=$value->datum_eerste_afgifte_nederland;
$item['Datumeerstetoelating']=$value->datum_eerste_toelating;
$item['Eerstekleur']=$value->eerste_kleur;
$item['Handelsbenaming']=$value->handelsbenaming; <--this value needs to be replaced in some cases
$item['Inrichting']=$value->inrichting;
$item['Kenteken']=$value->kenteken;
$item['Merk']=$value->merk;
}
$data = ['resource' => ($item)];
echo json_encode($data);
?>
Thanks!
Ps. Excuse my language, I'm from the Netherlands.
Related
I have a json file which I read in. I want to first filter the json data to return the object defined by the datasetID, then get out the datasetName. I have filtered in javascript, but would prefer to stay in php but I can't figure it out, any ideas?
note: foreach is not required as only a single record is returned when filtered using the datasetID. So rather than using a foreach method how would you swelect a single record, first for instance?
$datasetID = '5fd4058e5c8d2'; // unique 13 character string
$data = json_decode(file_get_contents(path/to/file), True);
So I need to first filter for the unique object with $datasetID = '5fd4058e5c8d2';
$filtered_data =
Then I need to return the attribute datasetName from that object
$datasetName =
pointers to the best ways to do this is welcomed.
Sample json data:
[
[
{
"datasetID":"5fd4124900827",
"institutionCode":"None",
"collectionCode":"None",
"datasetName":"None"
}
],
[
{
"datasetID":"5fd4058e5c8d2",
"institutionCode":"None",
"collectionCode":"None",
"datasetName":"None",
}
]
]
I don't know how you got that JSON but it is nested deeper than needed. You can merge the top level arrays to flatten it, then index on datasetID:
$data = array_merge(...$data);
$filtered_data = array_column($data, null, 'datasetID')[$datasetID];
$datasetName = $filtered_data['datasetName'];
Shorter:
$filtered_data = array_column(array_merge(...$data), null, 'datasetID')[$datasetID];
$datasetName = $filtered_data['datasetName'];
Or to keep them all to use:
$data = array_column(array_merge(...$data), null, 'datasetID');
$datasetName = $data[$datasetID]['datasetName'];
I tried with your sample JSON.
First, json_decode will return a PHP array to use foreach on it. I wrote a simple foreach and checked your searching ID is equal to element's datasetID. If it is equal this is the datasetName you are searching for.
<?php
$json = '[[{"datasetID":"5fd4124900827","institutionCode":"None","collectionCode":"None","datasetName":"None"}],[{"datasetID":"5fd4058e5c8d2","institutionCode":"None","collectionCode":"None","datasetName":"None"}]]';
$elements = json_decode($json,TRUE);
$searchingID = "5fd4058e5c8d2";
foreach ($elements as $element) {
if(isset($element[0]['datasetID']) && $element[0]['datasetID'] == $searchingID){
$filtered_data = $element[0];
break;
}
}
echo $filtered_data['datasetName']; // or return $filtered_data['datasetName'];
?>
Any idea on how to restructure the json below:
$jsonArray = [{"Level":"77.2023%","Product":"Milk","Temperature":"4"},
{"Level":"399.2023%","Product":"Coffee","Temperature":"34"},
{"Level":"109.2023%","Product":"Chocolate","Temperature":"14"}]
Expected outcome:
$expected = {"Milk":{"Level":"77.2023%","Temperature":"4"},
"Coffee":{"Level":"399.2023%","Temperature":"34"},
"Chocolate":{"Level":"109.2023%","Temperature":"14"}
}
I'm new and my thinking is get the product value in array and again use foreach loop to find the others value? .
Here's one possibility:
$jsonArray = '[{"Level":"77.2023%","Product":"Milk","Temperature":"4"},
{"Level":"399.2023%","Product":"Coffee","Temperature":"34"},
{"Level":"109.2023%","Product":"Chocolate","Temperature":"14"}]';
$output = array();
foreach (json_decode($jsonArray, true) as $row) {
$product = $row['Product'];
$output[$product] = $row;
unset($output[$product]['Product']);
}
echo json_encode($output);
Output:
{"Milk":{"Level":"77.2023%","Temperature":"4"},
"Coffee":{"Level":"399.2023%","Temperature":"34"},
"Chocolate":{"Level":"109.2023%","Temperature":"14"}
}
Demo on 3v4l.org
This made some trick
$a = '[{"Level":"77.2023%","Product":"Milk","Temperature":"4"},
{"Level":"399.2023%","Product":"Coffee","Temperature":"34"},
{"Level":"109.2023%","Product":"Chocolate","Temperature":"14"}]';
$newAr = array();
foreach(json_decode($a,true) as $key=>$value)
{
$newAr[$value['Product']] = array(
'Level' => $value['Level'],
'Temperature' => $value['Temperature'],
);
}
There are many ways to perform this with Loops in PHP. Other answers demonstrate it accurately. I would also suggest to integrate some form of Error handling, data validation/filtering/restriction in your code to avoid unexpected results down the road.
For instance, json_decode(), either assigned to a variable pre-foreach or straight in the foreach() 1st argument will just raise a warning if the original json is not valid-json, and just skip over the foreach used to construct your final goal. Then if you pass the result (that may have failed) directly to your next logic construct, it could create some iffy-behavior.
Also, on the concept of data-validation & filtering, you could restrict the foreach(), or any other looping mechanism, to check against a Product_List_Array[Milk,Coffee,Chocolate], using if(in_array() ...) so the final/goal object only contains the expected Products, this, in the case the original json has other artifacts. Filtering the values can also increase stability in restricting, for example, Temperature to Float.
I want to create a json object using php like below as I need to create a stacked bar chart using d3.js, hence I am using data from oracle table and need the json data as above image.
My table has these 3 columns. (ID, NAME, Layers) like:-
ID, NAME, Layers
1 ABC a:8,b:10
2 WWW c:8,d:7
When I am fetching data from oracle, my php code is:-
while (($row = oci_fetch_array($stid, OCI_ASSOC))) {
$streamArr[] = $row;
}
header("Access-Control-Allow-Origin: *");
echo json_encode($streamArr);
I am getting this error:-
Warning: [json] (php_json_encode) type is unsupported, encoded as null in line 48
json output as:-
[["1","ABC",{"descriptor":null}],["2","WWW",{"descriptor":null}]]
can you please help me in rectifying with this issue?
The error message refers to a field you didn't mention in the example. Maybe just don't select unneeded fields?
If you fix that, you still won't get the desired JSON structure. To get layers as an object in every element of data in the resulting JSON, you need to convert the string values stored in the database to PHP arrays before encoding.
You could do that with similar code:
while (($row = oci_fetch_array($stid, OCI_ASSOC)))
{
$row['layers'] = array_map(function($el) {
return explode(':', $el);
}, explode(',', $row['layers']));
$streamArr[] = $row;
}
#marekful answer is really nice, not easiest to understand but efficient and short!
Here you have a longer and not so efficient, but maybe easier to get.
$streamArr = array();
while (($row = oci_fetch_array($stid, OCI_ASSOC)))
{
// Get ID and NAME
$data = array(
'id' => $row['ID'],
'name' => $row['NAME'],
'layers' => array()
);
// Get Layers by split by comma
$layers = explode(',', $row['layers']);
foreach ($layers as $layer) {
// Get layer parts by slit with double-point
$layersPart = explode(':', $layer);
foreach ($layersPart as $key => $value) {
$data['layers'][$key] = $value;
}
}
// Add to global array
$streamArr[] = $data;
}
echo json_encode($streamArr);
I am having a problem with getting data from json. I cant change the way it is saved in the database since it is generated by the framework and after that read for the fields generation. My json looks like this:
{"102":{"textinput":{"comment":"2"}},"104":"34"}
OR
{"78":{"textinput":{"comment":"1"}},"82":"34"}
Comment value is my serialnumber that I net to get from this json. I tried with :
$json_sn = json_decode($customer_json_sn, true);
$snr = $json_sn['78']['textinput']['comment'];
But this is not the solution I need, since I never know the value of first numeric key, I cant rely on that. Any help would be appreciated.
If this format is going to be always the same, you can use reset() function on this one. Consider this example:
$json_sn = json_decode($customer_json_sn, true);
$snr = reset($json_sn);
echo $snr['textinput']['comment'];
How about:
$snr_array = array()
foreach ($json_sn as $key)
snr_array[] = $key['textinput']['comment'];
Edit: I just realized that you might just need/get one comment:
$key = key($json_sn);
$snr = $json_sn[$key]['textinput']['comment'];
You can do:
<?php
$json = '{"78":{"textinput":{"comment":"1"}},"82":"34"}';
var_dump(json_decode($json, true));
$data = json_decode($json, true);
foreach( $data as $key => $value ) {
# Check if exsit
if (isset($value['textinput']['comment'])) {
echo "Value: " . $value['textinput']['comment'];
}
}
I have a json like this:
[{"a":"1", "b":"2"},{"a":"4", "b":"5"},{"a":"15", "b":"2"}]
I want to get in php each row for update my database. I don't know the number of second level json are. Sometimes will be 1, sometimes 2 and sometimes more.
I thought, I could read it doing something like this:
$json = file_get_contents('php://input');
$json_post = json_decode($json, true);
$i = 0;
while(isset($json_post[$i])){
//Bla bla
$i++;
}
I have used many times json file in php but always, just one level. This is my first time with more than one.
But I can't. I know, because I checked, that in $json I have the complete json file.
You need to reference the subkey in your array:
$json = file_get_contents('php://input');
$json_post = json_decode($json, true);
$i = 0;
while(isset($json_post[$i])){
echo $json_post[$i]["a"];
// or
echo $json_post[$i][0];
$i++;
}
More docs can be found here: http://php.net/manual/en/language.types.array.php
And a similar question here: PHP reference specific key and value within multidimensional array
i'd use foreach:
foreach($json_post as $key => $value) {
echo $value;
}
$j = '[{"a":"1", "b":"2"},{"a":"4", "b":"5"},{"a":"15", "b":"2"}]';
$decoded = json_decode($j, true);
//var_dump($decoded);
foreach ($decoded as $key => $post) {
$valueOfA = $post['a'];
$valueOfB = $post['b'];
}