2

I am trying to get proper Json data from mysql. I made a lot of progress. Take a look;

I have table like below:

name             folder    path
RayMala          787       01.jpg,02.jpg,03.jpg,04.jpg,05.jpg...
RayMala          788       01.jpg,02.jpg,03.jpg,04.jpg,05.jpg,06.jpg...
Falitiko         332       01.jpg...
Falitiko         333       01.jpg,02.jpg...

My Current Code:Making array from single table cell.

$rows = array();
while($r = mysqli_fetch_assoc($result)) {   
    $rows[] = $r;
}

$nArray = array();
foreach($rows as $value){
    $nArray[] = array('name' => $value['name'], 'folder' => $value['folder'], 'path' => explode(",", $value['path']));
}

print json_encode($nArray);

Current JSON Output:See name value repeating.

[
    {
        "name": "RayMala",
        "folder": "787",
        "Paths": ["1.jpg", "2.jpg", "3.jpg"]
    },
    {
        "name": "RayMala",
        "folder": "788",
        "Paths": ["1.jpg", "2.jpg", "3.jpg"]
    },
    {
        "name": "Falitiko",
        "folder": "333",
        "Paths": ["1.jpg", "2.jpg", "3.jpg"]
    }
]

Wanted JSON Output:

[
    {
        "name":"RayMala",
        "random": [
            {
                "folder": "787",
                "Paths": ["1.jpg", "2.jpg", "3.jpg"]
            },
            {
                "folder": "788",
                "Paths": ["1.jpg", "2.jpg", "3.jpg"]
            }
        ]
    },
    {
        "name":"Falitiko",
        "random": [
            {
                "folder": "332",
                "Paths": ["1.jpg", "2.jpg", "3.jpg"]
            },
            {
                "folder": "333",
                "Paths": ["1.jpg", "2.jpg", "3.jpg"]
            }
        ]
    }
]
1
  • do it like this $nArray[$value['name']] = Commented Jun 13, 2015 at 10:39

1 Answer 1

2
$nArray = array();
while($r = mysqli_fetch_assoc($result)) {   
   $nArray[$r["name"]][] = array('folder' => $r['folder'], 'path' => explode(",", $r['path']));
}
$output_arr = array();
foreach($nArray as $key=>$value){
   $output_arr[]=array("name"=>$key,"random"=>$value);
}
echo json_encode($output_arr);
Sign up to request clarification or add additional context in comments.

2 Comments

Your answer is perfect but I forgot to add the name key. Because this way I cant call it in Angularjs. I edited the my Wanted Json Output. Could you edit your answer?
I added an additional foreach loop to get the names into the array. I don't know a way to do it in one loop as you have to check if the name is already existing then.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.