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
]
Related
I need one help.I have some JSON type data and i want to remove the duplicate set of data using PHP.I am explaining my code below.
data=[
{'member_name':member1,'no_of_users':20},
{'member_name':member1,'no_of_users':20},
{'member_name':member1,'no_of_users':20},
{'member_name':member2,'no_of_users':10},
{'member_name':member2,'no_of_users':10},
{'member_name':member3,'no_of_users':30},
]
my php side code is given below.
$res[]=array('member_name'=>$member,'no_of_members'=>$rowno['cnt']);
$result=var_dump( array_unique( $res, SORT_REGULAR ) );
//$result = json_decode($array, TRUE );
print json_encode($result);
Here we can see many duplicate data available.I need to remove only the duplicate data from this JSON object using PHP.Please help me.
First json_decode the JSON string, so we can work with it in PHP. Then you should use array_unique with the flag SORT_REGULAR to remove all duplicates and lastly json_encodeit again to a JSON string. Here's a working example:
$data = '[
{"member_name":"member1","no_of_users":20},
{"member_name":"member1","no_of_users":20},
{"member_name":"member1","no_of_users":20},
{"member_name":"member2","no_of_users":10},
{"member_name":"member2","no_of_users":10},
{"member_name":"member3","no_of_users":30}
]';
// Make a PHP array from the JSON string.
$array = json_decode( $data, TRUE );
// Only keep unique values, by using array_unique with SORT_REGULAR as flag.
// We're using array_values here, to only retrieve the values and not the keys.
// This way json_encode will give us a nicely formatted JSON string later on.
$array = array_values( array_unique( $array, SORT_REGULAR ) );
// Make a JSON string from the array.
$result = json_encode( $array );
Edit:
Based on your edit in your question:
Don't assign $result to a var_dump. Replace $result=var_dump( array_unique( $res, SORT_REGULAR ) ); by $result=array_unique( $res, SORT_REGULAR );
I was faced with the same challenge, so I came up with this simple solution.
<?php
//UniqueValues.php
class UniqueValues{
#The data Array
private $dataArray;
/*
The index you want to get unique values.
It can be the named index or the integer index.
In our case it is "member_name"
*/
private $indexToFilter;
public function __construct($dataArray, $indexToFilter){
$this->dataArray = $dataArray;
$this->indexToFilter = $indexToFilter;
}
private function getUnique(){
foreach($this->dataArray as $key =>$value){
$id[$value[$this->indexToFilter]]=$key;
}
return array_keys(array_flip(array_unique($id,SORT_REGULAR)));
}
public function getFiltered(){
$array = $this->getUnique();
$i=0;
foreach($array as $key =>$value){
$newAr[$i]=$this->dataArray[$value];
$i++;
}
return $newAr;
}
}
?>
include the class in your invocation code and that's all
<?php
//index.php
include_once('UniqueValues.php');
#Your JSON data
$data = '[
{"member_name":"member1","no_of_users":20},
{"member_name":"member1","no_of_users":20},
{"member_name":"member1","no_of_users":20},
{"member_name":"member2","no_of_users":10},
{"member_name":"member2","no_of_users":10},
{"member_name":"member3","no_of_users":30}
]';
#Convert your JSON to Array
$array = json_decode( $data, TRUE );
/*
Create an object by passing the "Two Dimension Array" in this case "$array" and
the "index" in this case "member_name" that you want to get the Unique Values
*/
$supper = new UniqueValues($array,"member_name");
/*
Get the unique valued array by calling the getFiltered() function
and encode it to JSON
*/
$result = json_encode( $supper->getFiltered() );
#Let the World See it :)
echo $result;
?>
Here, how can I solve this. See with example. make json unique
code part:
<?php
$depositeArray = array( 'deposite'=>array(
array('email'=>"sajib#gmail.com", 'deposite'=>0),
array('email'=>"avi#gmail.com", 'deposite'=>0),
array('email'=>"iqbal#gmail.com", 'deposite'=>0),
array('email'=>"balla#gmail.com", 'deposite'=>0),
array('email'=>"sajib#gmail.com", 'deposite'=>0),
array('email'=>"razib#gmail.com", 'deposite'=>0)
),
'total'=>0);
$depositeArray = json_encode($depositeArray);
$depositeArray = json_decode($depositeArray,true);
$depositeArrayNew = Json_Super_Unique($depositeArray['deposite'],'email');
$depositeArray['deposite'] = $depositeArrayNew ;
echo json_encode($depositeArray);
function Json_Super_Unique($array,$key){
$temp_array = array();
foreach ($array as &$v) {
if (!isset($temp_array[$v[$key]]))
$temp_array[$v[$key]] =& $v;
}
$array = array_values($temp_array);
return $array;
}
?>
i want return my data from mysql to json array with do while loop.
when i return one record with json it is well. but i want return list of array in one json array.
how can do that with index in while? my code have error and i don't know how can do it. with one record it is well but more can't.
$json="array(";
do{
$json=."'$row_query['id']'=>array('fname'=>$row_query['fname'],'lname'=>$row_query['lname']),";
} while ($row_query = mysqli_fetch_assoc($query));
json=.")";
echo json_encode($json,JSON_UNESCAPED_UNICODE);
There's no need to add quotes, brackets, parentheses or whatever. json_encode function will do it for you. Just provide an array to it:
$json = [];
while ($row_query = mysqli_fetch_assoc($query)) {
$json[$row_query['id']] = [
'fname'=>$row_query['fname'],
'lname'=>$row_query['lname'],
];
}
echo json_encode($json,JSON_UNESCAPED_UNICODE);
This is the most super easy version. You may try this.
$json = new array();
do{
array_push($json,$row_query);
} while ($row_query = mysqli_fetch_assoc($query));
or
$json = [];
do{
$json[] = $row_query;
} while ($row_query = mysqli_fetch_assoc($query));
Atlast encode your json variable.
$json = json_encode($json);
echo $json;
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 with the Following structure.
{
"1":{"Itemname":"dtfg","unitprice":"12","Qty":"4","price":"$48.00"},
"2":{"Itemname":"kjh","unitprice":"45","Qty":"7","price":"$315.00"},
"3":{"Itemname":"yjk","unitprice":"76","Qty":"8","price":"$608.00"},
"4":{"Itemname":"hgj","unitprice":"4","Qty":"45","price":"$180.00"}
}
I need the Itemname to be made into a PHP array, Unitprice into another one, Qty to another one and price to another one. How do I do that?
$getArray = get_object_vars(json_decode($json));
print_r($getArray);
echo $getArray[1]->Itemname;
echo $getArray[1]->unitprice;
you require get_object_vars as well for achieving your requirement.
<?php
$json =<<<JSONLIVES
{
"1":{"Itemname":"dtfg","unitprice":"12","Qty":"4","price":"$48.00"},
"2":{"Itemname":"kjh","unitprice":"45","Qty":"7","price":"$315.00"},
"3":{"Itemname":"yjk","unitprice":"76","Qty":"8","price":"$608.00"},
"4":{"Itemname":"hgj","unitprice":"4","Qty":"45","price":"$180.00"}
}
JSONLIVES;
$items = json_decode($json, TRUE);
$item_names = array();
foreach($items as $key => $item) {
$item_names[] = $item['Itemname'];
}
Or Php >= 5.5
print_r(array_column($items, 'Itemname'));
You need a function called json_decode() to convert your json data into PHP array
$json = {
"1":{"Itemname":"dtfg","unitprice":"12","Qty":"4","price":"$48.00"},
"2":{"Itemname":"kjh","unitprice":"45","Qty":"7","price":"$315.00"},
"3":{"Itemname":"yjk","unitprice":"76","Qty":"8","price":"$608.00"},
"4":{"Itemname":"hgj","unitprice":"4","Qty":"45","price":"$180.00"}
};
var_dump(json_decode($json));
You need to decode your Json by PHP's json_decode()
$decodeJson will return object then you can read Itemname and other values by using $val->Itemname in foreach loop
$json = '{
"1":{"Itemname":"dtfg","unitprice":"12","Qty":"4","price":"$48.00"},
"2":{"Itemname":"kjh","unitprice":"45","Qty":"7","price":"$315.00"},
"3":{"Itemname":"yjk","unitprice":"76","Qty":"8","price":"$608.00"},
"4":{"Itemname":"hgj","unitprice":"4","Qty":"45","price":"$180.00"}
}';
$decodeJson = json_decode($json);
foreach($decodeJson as $key=>$val) {
print_r($val);
}
Live Json decode
Try that:
$json = json_decode($json);
foreach($json as $obj){
echo $obj->name;
.....
}
After some research, I found out that the most efficientt way that solves my problem here would be to do like the following.
$cash=json_decode($new_json, true);
echo $arr3[1]['Itemname'];
echo $arr3[1]['unitprice'];
:
:
and so on.
This can be put into loops easily, fetched into HTML text-fields (as I want here in this scenario) and so on.
I have json string that I have to edit and then transform back to json. But unfortunately I can't really restore the json structure.
The structure of the original json string ($json):
"[{"Language":{"0":"EN"},"Text":{"0":"xxx"},"ContentType":{"0":"PlainText"}},
{"Language":{"0":"DE"},"Text":{"0":"xxx"},"ContentType":{"0":"PlainText"}},
{"Language":{"0":"FR"},"Text":{"0":"xxx"},"ContentType":{"0":"PlainText"}}]"
The structure I get after my edits ($newJson):
"{"0":{"Language":{"0":"EN"},"Text":{"0":"yyy"},"ContentType":{"0":"PlainText"}},
"1":{"Language":{"0":"DE"},"Text":{"0":"yyy"},"ContentType":{"0":"PlainText"}},
"2":{"Language":{"0":"FR"},"Text":{"0":"yyy"},"ContentType":{"0":"PlainText"}}}"
Here is what I do with my edits:
$jsonArray = object_to_array(json_decode($json));
$editedJsonArray = someLoopStuff($jsonArray);
$newJson = json_encode(array_to_object(($editedJsonArray)));
function object_to_array($obj) {
if(is_object($obj)) $obj = (array) $obj;
if(is_array($obj)) {
$new = array();
foreach($obj as $key => $val) {
$new[$key] = $this->object_to_array($val);
}
}
else $new = $obj;
return $new;
}
function array_to_object($a) {
if (is_array($a) ) {
foreach($a as $k => $v) {
$a[$k] = $this->array_to_object($v);
}
return (object) $a;
}
return $a;
}
Do you have an idea how I could get the same structure as the original json?
Use arrays instead of objects. Pass true to json_decode() as second argument and then do your stuff on arrays.
$jsonArray = json_decode($json, true);
Then just make your operation in loop on $jsonArray and simply use json_encode() without any additional work.
To achieve exactly same output as you have on input you need to cast subarrays on objects:
$jsonArray = json_decode('[{"Language":{"0":"EN"},"Text":{"0":"xxx"},"ContentType":{"0":"PlainText"}},{"Language":{"0":"DE"},"Text":{"0":"xxx"},"ContentType":{"0":"PlainText"}},{"Language":{"0":"FR"},"Text":{"0":"xxx"},"ContentType":{"0":"PlainText"}}]', true);
foreach ($jsonArray as &$item) {
foreach ($item as &$val) {
$val = (object) $val;
}
unset($val);
}
unset($item);
var_dump(json_encode($jsonArray));
Output:
string(226) "[{"Language":{"0":"EN"},"Text":{"0":"xxx"},"ContentType":{"0":"PlainText"}},{"Language":{"0":"DE"},"Text":{"0":"xxx"},"ContentType":{"0":"PlainText"}},{"Language":{"0":"FR"},"Text":{"0":"xxx"},"ContentType":{"0":"PlainText"}}]"
What if you would try to avoid using functions object_to_array and array_to_object. In the encoding part it is not necessary, because json_encode can handle objects or arrays. In the first part json_decode can be called with second optional parameter set to true to produce array instead of object. See PHP manual.