Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove repeat Json information?

Database :

`--> product table
id  name      cid     uploadKey
1   Cemera     1       7365
2   Notebook   2       7222`

`--> category table
id    catename
1      canon
2      toshiba`


`--> attactments table
id      uploadKey       filepath
1       7365            /img/jdf.png
2       7365            /img/sdsd.jpg`

This code to create json file:

$_GET['id']="1";
 $json_response = array();
    if(isset($_GET['id']))
    {
        $id=$_GET['id'];        
 $select = mysql_query("SELECT product.name,category.catename,attactments.filepath FROM product INNER JOIN category ON category.id = product.cid INNER JOIN attactments ON attactments.uploadKey = product.uploadKey where product.id='".$id."'  ");
    while ($row = mysql_fetch_array($select , MYSQL_ASSOC)) {       
        $json_response[] = $row;
         } 
    }
 echo $val= str_replace('\\/', '/', json_encode($json_response));

The result repeat information, how to remove repeat i want to show as below :

[{"name":"Cemera","catename":"canon","filepath":"/img/jdf.png"},{"name":"Cemera","catename":"canon","filepath":"/img/sdsd.jpg"}]

I want to show like this, how we edit it:

[{"name":"Cemera","catename":"canon","filepath":"/img/jdf.png","filepath":"/img/sdsd.jpg"}]
like image 296
DNu Avatar asked Jul 14 '15 04:07

DNu


People also ask

How do you remove duplicates from JSON in Java?

How to remove the duplicates? You will need to convert the JSON to Java Objects and then perform the duplicate removal operation. Added code snippet for each of the steps. Hope this helps!

Can JSON have duplicate fields?

The short answer: Yes but is not recommended. The long answer: It depends on what you call valid... [ECMA-404][1] "The JSON Data Interchange Syntax" doesn't say anything about duplicated names (keys).

Can JSON have repeated keys?

I've done some research and I understood that "duplicate" keys in JSON are legal, but different parsers act differently in handling this.


1 Answers

You can GROUP_CONCAT() filepath, try bellow code

$select = mysql_query("SELECT product.name,category.catename,GROUP_CONCAT(attactments.filepath SEPARATOR ',') AS filepath FROM product INNER JOIN category ON category.id = product.cid INNER JOIN attactments ON attactments.uploadKey = product.uploadKey where product.id='".$id."'  ");

while ($row = mysql_fetch_array($select , MYSQL_ASSOC)) {   
   $row['filepath'] = explode(',',$row['filepath']);
        $json_response[] = $row;
         } 

then you will get following result

{"name":"Cemera","catename":"canon","filepath":["\/img\/jdf.png","\/img\/sdsd.jpg"]}
like image 69
KTAnj Avatar answered Oct 14 '22 05:10

KTAnj