PHP: Check duplicate array key in objects array. - php

I have an objects array as following
[{"ChannelName":"39-40","Text":"haha"},
{"ChannelName":"39-40","Text":"lala"}
{"ChannelName":"40-41","Text":"bla bla"},
{"ChannelName":"40-41","Text":"kha kha"}]
How can I check duplicate value in ChannelName. What I need to do is when ChannelName exists in array object, I want to replace the ChannelName with new Text. How php check duplicate ChannelName and how to replace of old Text attribute with new Text attribute if ChannelName duplicate?

Try this solution.
$json = <<<JSON
[{"ChannelName":"39-40","Text":"haha"},
{"ChannelName":"39-40","Text":"lala"},
{"ChannelName":"40-41","Text":"bla bla"},
{"ChannelName":"40-41","Text":"kha kha"}]
JSON;
$json_array = json_decode( $json, TRUE );
$new_array = array();
$exists_array = array();
foreach( $json_array as $element ) {
if( !in_array( $element['ChannelName'], $exists_array )) {
$exists_array[] = $element['ChannelName'];
}
else{
$element['ChannelName'] = 'New Value';
}
$new_array[] = $element;
}
print json_encode( $new_array );
Here at New Value section you can change your value as per your requirement.

Related

replace value if same id in json over php

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.

Removing non-unique JSON object from file using PHP [duplicate]

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;
}
?>

PHP renaming string if string already exists

I am storing some data in an array and I want to add the key to it if the title already exists in the array. But for some reason it's not adding the key to the title.
Here's my loop:
$data = [];
foreach ($urls as $key => $url) {
$local = [];
$html = file_get_contents($url);
$crawler = new Crawler($html);
$headers = $crawler->filter('h1.title');
$title = $headers->text();
$lowertitle = strtolower($title);
if (in_array($lowertitle, $local)) {
$lowertitle = $lowertitle.$key;
}
$local = [
'title' => $lowertitle,
];
$data[] = $local;
}
echo "<pre>";
var_dump($data);
echo "</pre>";
You will not find anything here:
foreach ($urls as $key => $url) {
$local = [];
// $local does not change here...
// So here $local is an empty array
if (in_array($lowertitle, $local)) {
$lowertitle = $lowertitle.$key;
}
...
If you want to check if the title already exists in the $data array, you have a few options:
You loop over the whole array or use an array filter function to see if the title exists in $data;
You use the lowercase title as the key for your $data array. That way you can easily check for duplicate values.
I would use the second option or something similar to it.
A simple example:
if (array_key_exists($lowertitle, $data)) {
$lowertitle = $lowertitle.$key;
}
...
$data[$lowertitle] = $local;

Rebuild a json data remove duplicate value in one child node

Here is some json data:
[
{"a":"abc","b:":"10"},//"a":"abc"
{"a":"abd","b:":"12"},
{"a":"abc","b:":"14"},//"a":"abc"
{"a":"abe","b:":"15"},
{"a":"abf","b:":"16"},
{"a":"abg","b:":"17"},//"a":"abg"
{"a":"abg","b:":"19"}//"a":"abg"
]
I want remove all the duplicate values in the child node "a" (remain the first appear one).
Output =>
[
{"a":"abc","b:":"10"},//first appear "a":"abc"
{"a":"abd","b:":"12"},
{"a":"abe","b:":"15"},
{"a":"abf","b:":"16"},
{"a":"abg","b:":"17"}//first appear "a":"abg"
]
This is tested and appears to work as you've described:
$json = <<<JSON
[
{"a":"abc","b:":"10"},
{"a":"abd","b:":"12"},
{"a":"abc","b:":"14"},
{"a":"abe","b:":"15"},
{"a":"abf","b:":"16"},
{"a":"abg","b:":"17"},
{"a":"abg","b:":"19"}
]
JSON;
$json_array = json_decode( $json, TRUE );
$new_array = array();
$exists = array();
foreach( $json_array as $element ) {
if( !in_array( $element['a'], $exists )) {
$new_array[] = $element;
$exists[] = $element['a'];
}
}
print json_encode( $new_array );
It outputs [{"a":"abc","b:":"10"},{"a":"abd","b:":"12"},{"a":"abe","b:":"15"},{"a":"abf","b:":"16"},{"a":"abg","b:":"17"}], which I believe matches your desired output.

JSONPath Query to get Node-names?

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

Categories