2

I am trying to provide a count of certain sizes of lockers. My SQL statement is:

$sql = "SELECT Concat(`Height`, 'x', `Width`, 'x', `Depth`) as Locker, count(*) from lockers GROUP BY `Height`, `Width`, `Depth` ";

a var_dump in a loop of the rows gives me the following (many more rows are possible):

array(2) { ["Locker"]=> string(8) "15x30x45" ["count(*)"]=> int(6) }
array(2) { ["Locker"]=> string(8) "45x30x45" ["count(*)"]=> int(4) } 

I want to obtain a JSON string that looks like this:

{
  "SizeList": {
    "15x30x45": 6
    "45x30x45": 4
  }
}

I have tried a lot of different methods (including converting it into an object, but I can't get the value of the size as an index. For example, I get different variations of:

[0]=> string(31) "{"Locker":"15x30x45","count(*)":6}" 
[1]=> string(31) "{"Locker":"45x30x45","count(*)":4}"

Any help appreciated...

Chiwda
  • 1,233
  • 7
  • 30
  • 52

1 Answers1

1

You could just manually create the object like this:

$sizeList = new stdClass();
foreach ($results as $row) {
    $sizeList->{$row['Locker']} = $row['count(*)'];
}

echo json_encode(array('SizeList' => $sizeList));
Lawrence Johnson
  • 3,924
  • 2
  • 17
  • 30