5

我正在尝试为 jQuery 甘特图动态生成 json 数据。我知道 PHP,但对 JavaScript 完全陌生。我已经阅读了许多关于如何将数据动态添加到 json 的解决方案,并尝试了几十种组合,但什么也没有。这是json格式:

var data = [{
    name: "Sprint 0",
    desc: "Analysis",
    values: [{
        from: "/Date(1320192000000)/",
        to: "/Date(1322401600000)/",
        label: "Requirement Gathering", 
        customClass: "ganttRed"
        }]
    },{
    name: " ",
    desc: "Scoping",
    values: [{
        from: "/Date(1322611200000)/",
        to: "/Date(1323302400000)/",
        label: "Scoping", 
        customClass: "ganttRed"
        }]
    }, <!-- Somoe more data-->

      }];

现在我在 php db 结果中有所有数据。它是这样的:

$rows=$db->fetchAllRows($result);
$rowsNum=count($rows);

这就是我想从中创建 json 的方式:

var data='';
<?php foreach ($rows as $row){ ?>
data['name']="<?php echo $row['name'];?>";
data['desc']="<?php echo $row['desc'];?>";
data['values'] = {"from" : "/Date(<?php echo $row['from'];?>)/", "to" : "/Date(<?php echo $row['to'];?>)/", "label" : "<?php echo $row['label'];?>", "customClass" : "ganttOrange"};
}

但是,这不起作用。我试过不使用循环并用纯文本替换 php 变量只是为了检查,但它也不起作用。显示不添加项目的图表。如果我通过将新项目添加到值列表中来添加新项目,它就可以工作。所以甘特图本身或路径没有问题。基于以上所有,我认为问题在于向 json 添加纯数据。谁能帮我解决它?

4

4 回答 4

4

First of all you're adding properties to string instead of building object. If you really want to do that this way:

 var data = [], row;
 <?php foreach ($rows as $row) : ?>
     row = {};
     row.name ="<?php echo $row['name'];?>";
     row.desc ="<?php echo $row['desc'];?>";
     row.values = {"from" : "/Date(<?php echo $row['from'];?>)/", "to" : "/Date(<?php echo $row['to'];?>)/", "label" : "<?php echo $row['label'];?>", "customClass" : "ganttOrange"};
     data.push(row);
 <?php endforeach; ?>

Anyway it is unsafe (and result is normal JS code, not proper JSON object - but as you're assigning it to variable then I suppose it does not have to be in strict JSON format)

Better approach would be to build data structure in PHP and use json_encode function to generate JSON data for JavaScript:

 <?php
 $data = array();
 foreach ($rows as $row) {
      $data[] = array(
          'name'   => $row['name'],
          'desc'   => $row['desc'],
          'values' => array(array(
              'from'        => '/Date('.$row['from'].'>)/', 
              'to'          => '/Date('.$row['to'].')/',
              'label'       => $row['label'], 
              'customClass' => 'ganttOrange',
          ))
      );
 }
 ?>
 var data = <?php echo json_encode($data); ?>;
于 2012-11-26T23:01:26.690 回答
1

快速回答

如前所述,使用 PHP json_encode函数可以轻松解决此问题。

理解如何轻松做到这一点的诀窍是理解您尝试使用的复合数据结构。

概述

您正在处理的是一个通用的编程概念,称为“复合数据结构”。理解这一点的诀窍是要意识到您尝试管理的 PHP 和 JavaScript 只是完全相同事物的两种不同表示。

一旦这个概念深入人心,就很容易与用户Musadev-null-dweller已经解释过的内容联系起来。

解决这个问题的直接方法是在 PHP 中简单地构建一个复合数据结构,然后使用 PHP 的 json_encode 和 json_decode 的内置本机方法将其转换为 JSON(也称为 JavaScript)。

您应该将每个 $row 视为复合数据结构并使用 PHP json 函数,而不是执行所有语句。

下面的示例应该让您抢先一步,只需将其与您尝试使用的数据进行比较并相应地进行更改。

示例 001

  // This is a PHP composite data structure [ a nested array ]
  // represented in PHP. When you run this code you will get the
  // output of Result 001
  $user_profile = Array(
    main => Array(
      first_name  => "_blank_",
      last_name   => "_blank_",
      sex         => "_blank_",
      age         => "_blank_",    
    ),
    guardian => Array(
      first_name => "",
      last_name => "",
    ),
    children => Array(
      0 => Array(
        first_name => "Sally",
        last_name => "Shaw",
      ),
      1 => Array(
        first_name => "Scott",
        last_name => "Shaw",
      ),
    ),
  );

  // This is some sample PHP code you can use to modify
  // the composite data structure (modify the "_blank_" values)
  //
  $user_profile["main"]["first_name"] = "Archibald";
  $user_profile["main"]["last_name"]  = "Shaw";
  $user_profile["main"]["age"]        = "33";
  $user_profile["main"]["sex"]        = "male";

  // This is some sample PHP code you can use to modify
  // the composite data structure (add a new child)
  // 
  $user_profile["children"][2] = Array();
  $user_profile["children"][2]["first_name"]  = "Carrie";
  $user_profile["children"][2]["last_name"]   = "Shaw";

  // This is the PHP code you can use to transform from PHP to JSON 
  $result = json_encode( $user_profile );
  print_r( $result );

结果 001(为便于阅读而格式化)

{
   "main":{
      "first_name":"Archibald",
      "last_name":"Shaw",
      "sex":"male",
      "age":"33"
   },
   "guardian":{
      "first_name":"",
      "last_name":""
   },
   "children":[
      {
         "first_name":"Sally",
         "last_name":"Shaw"
      },
      {
         "first_name":"Scott",
         "last_name":"Shaw"
      },
      {
         "first_name":"Carrie",
         "last_name":"Shaw"
      }
   ]
}

结论

使用上面的示例,您应该首先对您尝试使用的 PHP 变量执行 print_r 并了解整体结构。一旦你知道了这一点,使用内置的 PHP json_encode 函数将其转换为 JSON 是一个简单的步骤。

参考

于 2012-11-26T23:32:09.460 回答
0
var data=[];

<?php 
foreach ($rows as $row)
{ 
    $obj = array(
        'name' => $row['name'],
        'desc' => $row['desc'],
        'values' => array(
            array(
                "from" => "/Date({$row['from']})/",
                "to" => "/Date({$row['to']})/",
                "label" => $row['label'],
                "customClass" => "ganttOrange",
            )
        )
    );
    $objJson = json_encode($obj);
    echo "data.push({$objJson});\n";
}
?>
于 2012-11-26T23:00:40.513 回答
0

您应该在 php 中创建数据结构并使用json_encode将其回显。

<?php 
$data = array();
foreach ($rows as $row){ 
    $item = array();
    $item['name']=$row['name'];
    $item['desc']=$row['desc'];
    $item['values']= array("from" => "/Date{$row['from']})/", 
                           "to" => "/Date({$row['to']})/", 
                           "label" => $row['label'], 
                           "customClass" => "ganttOrange");
    $data[] = $item;
}
echo "\nvar data = ".json_encode($data).";\n";
于 2012-11-26T23:00:47.133 回答