Search code examples
javascriptphparrayschap-links-libraryvis.js

Preparing an array for vis.js (PHP to JavaScript)


Trying to transfer data from a GraphDB (Neo4J) via PHP to JavaScript, so vis.js can be used to display those data.

I got so far:

  • Reading data from Neo4J and storem them in a PHP array:

Array
(
    [0] => Array
        (
            [0] => 550c2646c4985
            [1] => LOCAL_USER
        )

    [1] => Array
        (
            [0] => 550c267840b7a
            [1] => CSM
        )

    [2] => Array
        (
            [0] => 550c4e6e563b9
            [1] => TM
        )

    [3] => Array
        (
            [0] => 550c4e76b0701
            [1] => SM
        )

)

  • Browsing the net and found json_encode as the right function to transfer the data from PHP to JavaScript:

    var groups= <?php echo json_encode( $group_nodes ) ?>;

  • vis.js expects the data in an array like

  var nodes = [{
              id: 1,
              label: 'Node 1',
          }, {
              id: 2,
              label: 'Node 2'
          }, {
              id: 3,
              label: 'Node 3'
          }, {
              id: 4,
              label: 'Node 4'
          }, {
              id: 5,
              label: 'Node 5'
          }];

I stuck cause I couldnt find a way to get my array into readable format for vis.js. When I check the javascript array I got all elements, but only comma-separated. It seems vis.js expects them also in the syntax [{...,...},{...,...}].

Any idea how to generate such a format?


Solution

  • $newArray = array();
    
    for ($arrData as $value) {
       $newArray[] = array('id' => $value[0], 'label' => $value[1]);
    }
    
    $js = json_encode($newArray)