PHP code example of nexus-scholar / graph-core

1. Go to this page and download the library: Download nexus-scholar/graph-core library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

nexus-scholar / graph-core example snippets


use Mbsoft\Graph\Domain\Graph;

$graph = new Graph(directed: true);

$graph->addNode('A', ['label' => 'Node A']);
$graph->addNode('B', ['label' => 'Node B']);
$graph->addNode('C', ['label' => 'Node C']);

$graph->addEdge('A', 'B', ['weight' => 1.5]);
$graph->addEdge('B', 'C', ['weight' => 2.0]);
$graph->addEdge('C', 'A', ['weight' => 0.5]);

count($graph->nodes()); // 3
count($graph->edges()); // 3

if ($graph->hasEdge('A', 'B')) {
    $weight = $graph->edgeAttrs('A', 'B')['weight'];
}

$successors = $graph->successors('A');
$predecessors = $graph->predecessors('C');

use Mbsoft\Graph\Domain\Graph;

$graph = new Graph(directed: false);

$graph->addEdge('A', 'B', ['type' => 'friendship']);
$graph->addEdge('B', 'C', ['type' => 'friendship']);

$graph->hasEdge('A', 'B'); // true
$graph->hasEdge('B', 'A'); // true

$graph->successors('B');
$graph->predecessors('B');

use Mbsoft\Graph\Domain\Graph;

$edges = [
    ['A', 'B', ['weight' => 1.0]],
    ['B', 'C', ['weight' => 2.0]],
    ['C', 'D', ['weight' => 1.5]],
];

$graph = Graph::fromEdgeList($edges, directed: true);

use Mbsoft\Graph\Domain\Graph;
use Mbsoft\Graph\Domain\SubgraphView;

$graph = new Graph();
$graph->addEdge('A', 'B');
$graph->addEdge('B', 'C');
$graph->addEdge('C', 'D');

$subgraph = new SubgraphView($graph, ['A', 'B', 'C']);

$subgraph->nodes();
$subgraph->edges();
$subgraph->hasEdge('C', 'D'); // false

use Mbsoft\Graph\IO\CytoscapeJsonExporter;

$exporter = new CytoscapeJsonExporter();
$json = $exporter->export($graph);

use Mbsoft\Graph\IO\GraphMLExporter;

$exporter = new GraphMLExporter();
$xml = $exporter->export($graph);

use Mbsoft\Graph\IO\GexfExporter;

$exporter = new GexfExporter();
$xml = $exporter->export($graph);