php到json有两种特定的数据格式

时间:2017-01-02 06:11:24

标签: php json

我需要从php获得一个看起来完全像这样的JSON:

{
    "nodes": [
                {"x": 250, "y": 250, "color": "grey", "name":"1", "r":"28", "fixed":true},
                {"x": 120, "y": 150, "name":"somename", "score": -12.2, "icon": "someicon"},
                {"x": 140, "y": 150, "name":"someothername", "score": -0.08, "icon": "someothericon"}
            ],
    "links": [
                {"source":  0, "target": 1, "distance": 180},
                {"source":  0, "target": 2, "distance": 180},
                {"source":  0, "target": 2, "distance": 180}
            ]
}

我从db获取的节点数组,所以我之后做的是计算有多少,因为我必须为每个节点做一个链接(从1到n)。我尝试过这样做:(count($res)会给我一些节点)

$count = count($res);

for($i=1;$i<$count;$i++)
{

    $strings['source'] = 0;
    $strings['target'] = $i;
    $strings['distance'] = 180;

}   

在事先定义$strings = array();时,但这个计数器的作用是,它只会在数组中放置最后一个值,而实际上,我需要$count个,我需要保留这种特定格式,以便将其传递给JS进行进一步处理。

$res的内容如下。

  

([0] =&gt;数组([ID] =&gt; 67 [得分] => 0.05 [dscore] =&gt; 0.24 [xcord]   =&GT; 91 [ycord] =&gt; 391 [name] =&gt; somename [ticker] =&gt; tickname [icon] =&gt; someicon [datafrom] =&gt; 2017-01-01)[1] =&gt;数组([ID] =&gt; 68 [得分]   =&GT; -0.32 [dscore] =&gt; 0.55 [xcord] =&gt; 120 [ycord] =&gt; 428 [name] =&gt; othername [ticker] =&gt; tickname [icon] =&gt; someothericon [datafrom] =&gt;   2017-01-01)[2] =&gt;数组([ID] =&gt; 69 [得分] =&gt; -0.32 [dscore] =&gt;   0.21 [xcord] =&gt; 482 [ycord] =&gt; 268 [name] =&gt; mysanantonio [ticker] =&gt; tickname [icon] =&gt;其他一些图标[datafrom] =&gt; 2017-01-01)

我需要

  1. 循环$i次,并为每个循环增加值     target中的links乘以
  2. 合并两个数组以获取JSON     输出与在beggining
  3. 中显示的输出相同

1 个答案:

答案 0 :(得分:1)

你应该让$strings成为一个二维数组。

$k = 0;
for($i=1;$i<$count;$i++) {

    $strings[$k]['source'] = 0;
    $strings[$k]['target'] = $i;
    $strings[$k]['distance'] = 180;
    $k++;
}   

$strings = array_values( (array)$strings );
echo json_encode($strings);