Creating array inside array from mysql data to json

早过忘川 提交于 2020-01-07 03:49:11

问题


I am trying to create json with php from two mysql tables:
- Category(unique)
- Subcategories or Rights(multiple in same category)

But I can't list multiple subcategories under one category. Instead, for every subcategory new set of results is made that contains category data also.
This is php code:

$sql = "SELECT a.id as rid,a.name as rname,a.img as rimg,a.price,b.id as cid,b.name as cname FROM rights a INNER JOIN categories b ON a.category=b.id";

$result = $mysqli->query($sql);
    if ($result->num_rows > 0) {
        $json_response = array();
        while($row = $result->fetch_assoc()) {
            $row_array['idCategory'] = $row['cid'];
            $row_array['nameCategory'] = $row['cname'];
            $row_array['rights'] = array([
                'idRight' => $row['rid'],
                'name' => $row['rname'],
                'price' => $row['price'],
                'image' => $row['rimg']
            ]);

            array_push($json_response,$row_array);
        }

        echo json_encode($json_response);
    }

With this I am getting:

[{
    "idCategory": "1",
    "nameCategory": "Cat1",
    "rights": [{
        "idRight": "1",
        "name": "Right1 in Cat1",
        "price": "10",
        "image": "img1.jpg"
    }]
}, {
    "idCategory": "2",
    "nameCategory": "Cat2",
    "rights": [{
        "idRight": "2",
        "name": "Right1 in Cat2",
        "price": "20",
        "image": "img2.jpg"
    }]
}, {
    "idCategory": "2",
    "nameCategory": "Cat2",
    "rights": [{
        "idRight": "3",
        "name": "Right2 in Cat2",
        "price": "30",
        "image": "img3.jpg"
    }]
}]

I tried changing mysql select with GROUP_CONCAT and GROUP BY but then I get data in one row like this:

"rights": [{
            "idRight": "2,3",
            "name": "Right1 in Cat2,Right2 in Cat2",
            "price": "20,30",
            "image": "img2.jpg,img3.jpg"
        }]

But I need it like this:

[{
    "idCategory": "1",
    "nameCategory": "Cat1",
    "rights": [{
        "idRight": "1",
        "name": "Right1 in Cat1",
        "price": "10",
        "image": "img1.jpg"
    }]
}, {
    "idCategory": "2",
    "nameCategory": "Cat2",
    "rights": [{
        "idRight": "2",
        "name": "Right1 in Cat2",
        "price": "20",
        "image": "img2.jpg"
    },
    {
        "idRight": "3",
        "name": "Right2 in Cat2",
        "price": "30",
        "image": "img3.jpg"
    }]
}]

How to achieve that?


回答1:


You need to remap your array and then initialize an array for the rights key... so, change your while loop something like this:

$json_response = array();
while($row = $result->fetch_assoc()) {
    if (!isset($json_response[ $row['idCategory'] ])) {
        $json_response[ $row['idCategory'] ] = [
            'idCategory' => $row['idCategory'],
            'nameCategory' => $row['nameCategory'],
            'rights' => [],
        ];
    }
    $json_response[ $row['idCategory'] ]['rights'][] = [
        'idRight' => $row['rid'],
        'name' => $row['rname'],
        'price' => $row['price'],
        'image' => $row['rimg']
    ];
}

// We want the final result to ignore the keys and to create a JSON array not a JSON object 
$data = [];
foreach ($json_response as $element) {
    $data[] = $element;
}

echo json_encode($data);

This part of the code $json_response[ $row_array['idCategory'] ] helps to maintain a unique grouping of the data because it creates a hash based on the idCategory. An array can only have one key and since idCategory is always unique we can use that as the key for grouping on. Then because we now have a hash-based array, we have to create a new array that is a 'real' array for when it is converted to JSON. You do not want to use GROUP BY or GROUP_CONCAT in this situation.




回答2:


I revised the code above to fit my needs, but I am having trouble to make another array of that array...

from: ...

$json_response[ $row['idCategory'] ]['rights'][] = [
    'idRight' => $row['rid'],
    'name' => $row['rname'],
    'price' => $row['price'],
    'image' => $row['rimg']
];

to:

    $json_response[ $row['regCode'] ]['provinces'][] = $row['provDesc'];

actually this is a follow up question, how about array inside array of that array...

like this:

[
 {
  rid: "1",
  region: "REGION I", //array 1
  provinces: [
       {
        pid: "128", 
        province: "ILOCOS NORTE", //array 2
        cities[
              "Adams", //array 3
              "Bacarra"
             ],
       "ILOCOS SUR"
      ]
 },
 {
  rid: "2",
  region: "REGION II",
  provinces: [
       "BATANES",
       "CAGAYAN"
      ]
 }

]



来源:https://stackoverflow.com/questions/34668484/creating-array-inside-array-from-mysql-data-to-json

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!