I tried to replace a json value if the id from json1 same with json2 than replace the name in json1, here my json:
$json1 = '[{"categoryId":"10","name":"Technology"},{"categoryId":"10","name":"Blog"},{"categoryId":"11","name":"Programming"}]';
$json2 = '[{"categoryId":"10","name":"Tech"}]';
My expected result is:
$json1 = '[{"categoryId":"10","name":"Tech"},{"categoryId":"10","name":"Tech"},{"categoryId":"11","name":"Programming"}]';
I did with javascript so far:
json1.forEach(function(json1) {
if (json2.categoryId === json1.categoryId) {
json1.name = json2.name
}
});
but how to do it over php language?
This will help you I hope
// Your json data
$json1 = '[{"categoryId":"10","name":"Technology"},{"categoryId":"11","name":"Blog"},{"categoryId":"12","name":"Programming"}]';
$json2 = '[{"categoryId":"10","name":"Tech"}]';
// Turn json into an array
$array1 = json_decode($json1, true);
$array2 = json_decode($json2, true);
// Loop to json2 as array
foreach ($array2 as $value) {
$categoryId = $value['categoryId'];
// Check if the categoryId exist in array 1 and get the index key
$key = array_search($categoryId, array_column($array1, 'categoryId'));
// Check if the key exist ena check if it has a name to be changed
if (isset($array1[$key]) && isset($array1[$key]['name'])) {
// Set the new name
$array1[$key]['name'] = $value['name'];
}
}
// Turn the array back into json
$json1 = json_encode($array1);
Did your solution work in JS? It seems to me, that in the loop, you should be comparing with the first entry of the json2 variable, as the whole json2 is a list of objects and does not itself have a name property.
In PHP, this could work like this:
$arr1 = json_decode($json1);
$arr2 = json_decode($json2);
$arr2entry = $arr2[0]; # this is what we want to compare against
foreach ($arr1 as &$arr1entry) { #[1]
if ($arr2entry["categoryId"] == $arr1entry["categoryId"]) {
$arr1entry["name"] = $arr2entry["name"];
}
}
#[1] notice the ampersand here, that's a reference assignment,
#it is needed to actually modify the content of the original array.
Related
Array : [{"ID":1},{"ID":2}]
$id=1;
I want to check if $id exists in the array.
Thank you!
You may try Laravel's Collection::contains method, for example:
$collection = collect(json_decode($jsonString, true));
if ($collection->contains(1) {
// Exists...
}
Also, you may use key/value pair like this:
if ($collection->contains('ID', 1) {
//...
}
Also, if you want to get that item from the collection then you may try where like this:
$id = $collection->where('ID', 1)->first(); // ['ID' => 1]
You have a json formatted array and you need to decode it using json_decode first. After that loop the array to check for the id that you want.
So the code should look like this:
$json = '[{"ID":1},{"ID":2}]';
$id = 1;
$data = json_decode($json, true);
foreach($data as $item){
if($item['id'] == $id) {
echo 'it exists';
}
}
Iterate the array using for loop and use the value as a param to json_decode.
$id = 1;
$arr = array('{"ID":1}', '{"ID":2}');
foreach($arr as $val) {
if (in_array($id, json_decode($val, TRUE))) {
echo "id present";
}
}
Try this, if value is exist it will give key of array
$jsondata = '[{"ID":1},{"ID":2}]';
$array = json_decode($jsondata,true);
$key = array_search(1, array_column($array, 'ID'));
Just check if the string is in the json array, with little computation.
I think it's the more efficient way. Check the result here.
<?php
$id = 1;
$array = ['{"ID":1}', '{"ID":2}'];
echo in_array(json_encode(["ID" => $id]), $array) ? 'Yes' : 'No';
I have the following structure in JSON:
[
{
"id":"79",
"value":"val1"
},
{
"id":"88",
"value":["val1","val2","new"]
}
]
How to handle this cases? I've tried this but it only handle the first case:
<?php
$arr = json_decode($json_string);
$itemsList = new stdClass;
$i_d=0;
foreach ($arr as $key=>$arrj):
$itemsList->id[$i_d] = $arrj->id;
$itemsList->value[$i_d] = $arrj->value;
$i_d++;
endforeach;
?>
Thanks in advance.
Inside your foreach loop, you can check that $arrj->value is an array. If it is, you can loop over it and add its values into your result object one by one, and if it isn't, you can add the single value as you already are.
<?php
$arr = json_decode($json_string);
$itemsList = new stdClass;
foreach ($arr as $key=>$arrj):
$itemsList->id[] = $arrj->id;
if (is_array($arrj->value)) { // Is it an array?
foreach ($arrj->value as $value) { // If so, add its values in a loop
$itemsList->value[] = $value;
}
} else {
$itemsList->value[] = $arrj->value; // if not, just add the single value
}
endforeach;
?>
I removed the $i_d variable; it is unnecessary because PHP will automatically create numeric indices beginning with 0 when you add values to an array using [].
I'm on PHP and I need to edit a JSON output to return only objects >=0 and divided by one hundred
Eg.
$json = {"data":[0,55,78,-32,-46,37]}
Needed
$json = {"data":[0,0.55,0.78,0.37]}
How this can be done?
Well, I know this is not the best practice, but if it's as simple as this, you can do the following.
$json = '{"data":[0,55,78,-32,-46,37]}';
// decoding the string to objects & arrays
$x = json_decode($json);
// applying a function on each value of the array
$x->data = array_map(
function($a)
{
if( $a >= 0 ) return $a/100;
else return null;
},
$x->data
);
// Removing empty values of the array
$x->data = array_filter($x->data);
// making a JSON array
$jsonData = json_encode(array_values($x->data));
// inserting a JSON array in a JSON Object
$json = '{"data":' . $jsonData . '}';
// here is your {"data":[0,0.55,0.78,0.37]}
echo $json;
Hope it helps !
Btw, I had to trick the json encode with array_values to prevent the creation of an object rather than an array for the data content. But I guess there is a better method that I just don't know ...
EDIT :
Find out the way :D
Once empty values removed from the array, just do :
$x->data = array_values($x->data);
$json = json_encode($x);
This will do the trick and it will not create issues with the rest of the object.
Alessandro:
Here's my approach, feel free to try. json_decode and a simple foreach can help you...
Code:
$json = array();
$result = array();
$json = '{"data":[0,55,78,-32,-46,37]}';
$decoded_json=json_decode($json, TRUE);
foreach ($decoded_json['data'] as &$value) {
if ($value >= 0){
$value = $value / 100;
$result[]=$value;
}
}
echo json_encode($result);
?>
Result:
[0,
0.55,
0.78,
0.37
]
So I am trying to make, code will get certain parts matching ID's from the JSON array.
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
$response = curl_exec($ch);
curl_close($ch);
$json = json_decode($response, true);
//-------------------------------------
$invIndexes = [];
foreach($json->rgInventory as $index){
$invIndexes = $index;
}
//-------------------------------------
$makearray = (array)$invIndexes;
for($id = 0;$id < count($invIndexes);$id++){
$index = $makearray[$id];
$item = $json->rgDescriptions[$json->rgInventory[$index]->classid + "_" + $json->rgInventory[$index]->instanceid];
if($item->tradeable != 1){
continue;
}
$ItemName = $item->market_hash_name;
}
var_dump($ItemName);
Here's the JSON: http://pastebin.ca/3591035
The $ItemName return's NULL but it shouldn't (At least I think that). Maybe someone can spot the mistake what I've been doing here :/
If you are you using true in json decode $json = json_decode($response, true);, then it will return an associative array, so you can access the value form array simply like this $json['rgInventory'] not $json->rgInventory
To create $invIndexes array use this:
$invIndexes = array();
foreach($json['rgInventory'] as $index){
$invIndexes[] = $index['id'];
}
Here you will get $invIndexes the in your for loo you are again using $json->rgDescriptions to access values, change this to $json['rgInventory'] and for all other values use array keys like this $json['rgInventory']['index']['class']
No need of this $makearray = (array)$invIndexes; directly use $invIndexes
$index = $invIndexes[$id];
$item = $json['rgDescriptions'][$json['rgInventory'][$index]['classid']."_".$json['rgInventory'][$index]['instanceid']];
Another mistake is that in your $item there is not any key tradeable, its tradable an use like this
if($item['tradeable'] != 1){
continue;
}
$ItemName = $item['market_hash_name'];
At last var_dump($ItemName);
The second argument true to json_decode tells it to convert JSON objects into PHP associative arrays rather than PHP objects. But using syntax like $json->rgDescriptions requires $json to be an object; for an array it should be $json['rgDescriptions'].
So either change all your uses of $json to use array syntax, or remove the true argument from json_decode. The latter should be easier.
Also, this line:
$invIndexes = $index;
should be:
$invIndexes[] = $index;
But you could replace that loop with just:
$invIndexes = $json->rgInventory;
I have a .json file with player name, mail address, field name and score on that field. Like this:
{"0":{"name":"test","password":"test","mail":"test#test.test","test3":0,"test2":0},"1":{"...
I want to change the score at one field, but I can't. I tried this way:
$jsonn = file_get_contents('data/userdata.json');
$arrayy = json_decode($jsonn, true);
$field = $_SESSION['fieldname'];
$arrayy[$felhasznev][$palya] = $pontszam;
And I also tried this but not helped:
$jsonn = file_get_contents('data/userdata.json');
$arrayy = json_decode($jsonn, true);
$field = $_SESSION['fieldname'];
foreach ($arrayy as $key => $valuee){
if($valuee['name'] == $username){
$valuee[$field] = $score;
}
}
I'm beginner in JSON so maybe something trivial...
Function json_decode parse json file to objects, you're using associative array, to have an associative array you have to pass a second argument as true, like:
<?php
$file = file_get_contents("file.json");
$players = json_decode($file, true);
$err = json_last_error();
if ($err != JSON_ERROR_NONE) {
print_r($err);
die("Error in json file :/");
}
var_dump($players);
foreach ($players as $key => $val) {
if ($players[$key]["name"] == "test") {
$players[$key]["test3"] = $players[$key]["test3"] + 1;
$players[$key]["test2"] = $players[$key]["test2"] + 1;
}
}
var_dump($players);
file_put_contents("new_file.json", json_encode($players));
(1) In your sample json, there is value (0) not enclosed in double quote (parsing error!).
(2) the first code should work if json is ok.
(3) in the second code, you skipped the "id" identifier (if json is ok).