Sanjib Behera
Sanjib Behera

Reputation: 101

Need to create Json object in php

enter image description here

I want to create a json object using php like below as I need to create a stacked bar chart using d3.js, hence I am using data from oracle table and need the json data as above image.
My table has these 3 columns. (ID, NAME, Layers) like:-

ID, NAME, Layers
1   ABC   a:8,b:10
2   WWW   c:8,d:7

When I am fetching data from oracle, my php code is:-

while (($row = oci_fetch_array($stid, OCI_ASSOC))) {
          $streamArr[] = $row;
}    
header("Access-Control-Allow-Origin: *");
echo json_encode($streamArr);

I am getting this error:-

Warning: [json] (php_json_encode) type is unsupported, encoded as null in line 48
json output as:-
[["1","ABC",{"descriptor":null}],["2","WWW",{"descriptor":null}]]
can you please help me in rectifying with this issue?

Upvotes: 1

Views: 980

Answers (2)

Camille
Camille

Reputation: 2531

@marekful answer is really nice, not easiest to understand but efficient and short!

Here you have a longer and not so efficient, but maybe easier to get.

$streamArr = array();
while (($row = oci_fetch_array($stid, OCI_ASSOC))) 
{
    // Get ID and NAME
    $data = array(
        'id' => $row['ID'],
        'name' => $row['NAME'],
        'layers' => array()
    );
    // Get Layers by split by comma
    $layers = explode(',', $row['layers']);
    foreach ($layers as $layer) {
        // Get layer parts by slit with double-point
        $layersPart = explode(':', $layer);
        foreach ($layersPart as $key => $value) {
            $data['layers'][$key] = $value;
        }
    }
    // Add to global array
    $streamArr[] = $data;
}
echo json_encode($streamArr);

Upvotes: 1

marekful
marekful

Reputation: 15361

The error message refers to a field you didn't mention in the example. Maybe just don't select unneeded fields?

If you fix that, you still won't get the desired JSON structure. To get layers as an object in every element of data in the resulting JSON, you need to convert the string values stored in the database to PHP arrays before encoding.

You could do that with similar code:

while (($row = oci_fetch_array($stid, OCI_ASSOC))) 
{
  $row['layers'] = array_map(function($el) {
    return explode(':', $el);
  }, explode(',', $row['layers']));

  $streamArr[] = $row;
}

Upvotes: 1

Related Questions