i have this JSON
[
{"name":"Juan","Sex":"Male","ID":"1100"},{"name":"Maria";"Sex":"Female","ID":"2513"},{"name":"Pedro";"Sex":"Male","ID":"2211"}
]
I want to get only those with this ID 2513
[
{"name":"Maria";"Sex":"Female","ID":"2513"}
]
Your JSON String is invalid. First replace all the semicolons ; with comma , and then try using array_filter() or any other way e.g foreach() with if condition etc. I've used the array_filter() way, hope it helps :)
<?php
$json = '[{"name":"Juan","Sex":"Male","ID":"1100"},{"name":"Maria","Sex":"Female","ID":"2513"},{"name":"Pedro","Sex":"Male","ID":"2211"}]';
$array = json_decode($json,1);
$ID = 2513;
$expected = array_filter($array, function ($var) use ($ID) {
return ($var['ID'] == $ID);
});
print_r($expected);
?>
DEMO: https://3v4l.org/kZrMo
Use json_decode() to convert the JSONString to a PHP array of objects
$str = '[{"name":"Juan","Sex":"Male","ID":"1100"},"name":"Maria";"Sex":"Female","ID":"2513"},{"name":"Pedro";"Sex":"Male","ID":"2211"}]';
$arr = json_decode($str);
foreach ( $arr as $obj ){
if ( $obj->ID == 2513 ) {
echo $obj->name;
}
}
Related
i really need help about arrays. I have a case like this
[
{"animal":"lion", "car":"honda"},
{"animal":"rabbit","car":"BMW"},
{"animal":"rat", "car":"Toyota"},
{"animal":"mouse", "car":"Suzuki"},
{"animal":"horse", "car":"mercedes"},
{"animal":"dog", "car":"Jaguar"},
{"animal":"cat", "car":"Audi"}
]
how in php code it can split become 2 category like this
$animal = [ "lion","rabbit","rat","mouse","horse","dog","cat"];
and
$car = ["honda","BMW","Toyota","Suzuki","mercedes","Jaguar","Audi"];
I really need to solve this. please help me
Json_decode the string and use array_column to get the columns in each variable.
$json = '[
{"animal":"lion", "car":"honda"},
{"animal":"rabbit","car":"BMW"},
{"animal":"rat", "car":"Toyota"},
{"animal":"mouse", "car":"Suzuki"},
{"animal":"horse", "car":"mercedes"},
{"animal":"dog", "car":"Jaguar"},
{"animal":"cat", "car":"Audi"}
]';
$arr = json_decode($json,1);
$animals = array_column($arr, "animal");
$cars = array_column($arr, "car");
var_dump($cars, $animals);
https://3v4l.org/NtL9e
Real easy. Decode the json, create two blank arrays, loop through, and add to each array:
<?php
$x = '[
{"animal":"lion", "car":"honda"},
{"animal":"rabbit","car":"BMW"},
{"animal":"rat", "car":"Toyota"},
{"animal":"mouse", "car":"Suzuki"},
{"animal":"horse", "car":"mercedes"},
{"animal":"dog", "car":"Jaguar"},
{"animal":"cat", "car":"Audi"}
]';
$y = json_decode($x, true);
$animals = [];
$cars = [];
foreach ($y as $z) {
$animals[] = $z['animal'];
$cars[] = $z['car'];
}
var_dump($animals);
var_dump($cars);
https://3v4l.org/Fb7Bq
try that:
$arr=json_decode('[
{"animal":"lion", "car":"honda"},
{"animal":"rabbit","car":"BMW"},
{"animal":"rat", "car":"Toyota"},
{"animal":"mouse", "car":"Suzuki"},
{"animal":"horse", "car":"mercedes"},
{"animal":"dog", "car":"Jaguar"},
{"animal":"cat", "car":"Audi"}
]');
var_dump($arr);echo'<br>';echo'<br>';
$animal=array();
$car=array();
foreach ($arr as $row){
$animal[]=$row->animal;
$car[]=$row->car;
}
var_dump($car);
var_dump($animal);
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;
}
?>
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'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
]
Consider the following piece of JSONPath:
{
"result":[
{
"type":"Residence",
"street":"Piazza di Spagna",
"city":"-4:0"
},
{
"type":"Residence",
"street":"test",
"city":"-4:1"
}
]
}
Is it possible to get a list of all the node-names?
So for example, I want a list like: type, street, city.
Try this
$arr = (json_decode($json)->result[0]);
$array = get_object_vars($arr);
$properties = array_keys($array);
print_r($properties);`
Out put will be
Array
(
[0] => type
[1] => street
[2] => city
)
On PHP >= 5.4 you can obtain your keys with one line of code:
$nodeNames = array_keys( json_decode( $jsonString, True )['result'][0] );
3v4l.org demo
On lower versions (PHP >= 5.2.16), you have to break above code in two lines:
$array = json_decode( $jsonString, True );
$nodeNames = array_keys( $array['result'][0] );
I decode the JSON string with second parameter as True to force result as array, then I call array_keys to obtain the keys of array['result'][0].
Edit: more flexibility
Your example can be processed as above without problems, but what happens if original JSON string has different keys? The above solution will fail if in the first result row there are not all the keys. To obtain all the keys, you can use this code:
$array = json_decode( $jsonString, True );
$nodeNames = array();
foreach( $array['result'] as $row )
{
$nodeNames = array_unique( array_merge( $nodeNames, array_keys( $row ) ) );
}
or, using array_filter, with this code:
$array = json_decode( $jsonString, True );
$nodeNames = array();
array_filter
(
$array['result'],
function( $row )
{
global $nodeNames;
$nodeNames = array_unique( array_merge( $nodeNames, array_keys( $row ) ) );
}
);
By this two equivalent examples, I process each result row, merging the keys in $nodeNames array and using array_unique to delete duplicate keys.
Read more about array_keys()
Read more about array_unique()
Read more about array_filter()
You can use following function to print all keys in an array format
print_r(array_keys($array));
Is the JSON Path definitely going to follow that structure every time? As in Result => Arrays all of which have the same Nodes.
If it does then the following will work:
function getJsonNodes($json) {
$nodes = array();
$decoded = json_decode($json, true);
if (json_last_error() !== JSON_ERROR_NONE) {
throw new \InvalidArgumentException('Invalid JSON String passed to getJsonNodes()');
}
$result = $decoded['result'];
if (is_array($result)) {
$nodes = array_keys($result[0]);
}
return $nodes;
}
Usage would be something like:
try {
$nodes = getJsonNodes($json);
} catch (\InvalidArgumentException $e) {
echo $e->getMessage();
}
Means you can catch any Invalid JSON strings that could potentially be passed and mess with the output.
Although as I stated, the above solution will only work if your JSON Path follows the structure to put in your OP.
You can see it in use here: https://ideone.com/dlvdu2
Hope it helps either way.
Is it possible to get a list of all the node-names?
$object = json_decode($json);
$json_array = $object->result;
foreach ($json_array as $key => $value) {
$object_var = get_object_vars($value);
$object_key = array_keys($object_var);
var_dump($object_key);//will get all node_names!
}
Try this
$result[0].type , $result[0].street, $result[0].city
Please check the below code ..Hope will work
<?php
$text[]=array(
result=>array(
"type"=>"Residence",
"street"=>"pizza",
"city"=>"ini"
),
array(
"type"=>"Residence",
"street"=>"pizza",
"city"=>"ini"
)
);
echo json_encode($text);
?>