最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Dynamically add data stored in php to nested json - Stack Overflow

programmeradmin0浏览0评论

I am trying to dynamicaly generate data in json for jQuery gantt chart. I know PHP but am totally green with JavaScript. I have read dozen of solutions on how dynamicaly add data to json, and tried few dozens of binations and nothing. Here is the json format:

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-->

      }];

now I have all data in php db result. Here it goes:

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

And this is how I wanted to create json out of it:

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"};
}

However this does not work. I have tried without loop and replacing php variables with plain text just to check, but it did not work either. Displays chart without added items. If I add new item by adding it to the list of values, it works. So there is no problem with the Gantt itself or paths. Based on all above I assume the problem is with adding plain data to json. Can anyone please help me to fix it?

I am trying to dynamicaly generate data in json for jQuery gantt chart. I know PHP but am totally green with JavaScript. I have read dozen of solutions on how dynamicaly add data to json, and tried few dozens of binations and nothing. Here is the json format:

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-->

      }];

now I have all data in php db result. Here it goes:

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

And this is how I wanted to create json out of it:

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"};
}

However this does not work. I have tried without loop and replacing php variables with plain text just to check, but it did not work either. Displays chart without added items. If I add new item by adding it to the list of values, it works. So there is no problem with the Gantt itself or paths. Based on all above I assume the problem is with adding plain data to json. Can anyone please help me to fix it?

Share Improve this question asked Nov 26, 2012 at 22:48 HoGoHoGo 9514 gold badges11 silver badges17 bronze badges 1
  • 4 You should create the data structure in php and echo it out with json_encode. – Musa Commented Nov 26, 2012 at 22:53
Add a ment  | 

4 Answers 4

Reset to default 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); ?>;

Quick Answer

As stated previously, this problem is easily resolved using the PHP json_encode function.

The trick to understanding how to do this easily is to understand the posite data structure that you are trying to work with.

Overview

What you are dealing with is a general programming concept called a "posite data structure". The trick to understanding this is to realize that the PHP and the JavaScript that you are attempting to manage are just two different representations of the exact same thing.

Once this concept sinks in, it will be easy to relate to what the users Musa and dev-null-dweller have already explained.

The straightforward way to solve this issue is to simply build a posite data structure in PHP and then translate it into JSON (aka JavaScript) using the built-in native methods of PHP's json_encode and json_decode.

Instead of doing all the statements, you should treat each $row as a posite data structure and use the PHP json functions.

The following example should give you a head start, simply pare it to the data you are trying to work with and change accordingly.

Example 001

  // This is a PHP posite 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 posite 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 posite 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 );

Result 001 (formatted for easy readability)

{
   "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"
      }
   ]
}

Conclusion

Using the example above, you should first do a print_r of the PHP variable you are trying to work with and get an idea of the overall structure. Once you know this, it is an easy step to convert it to JSON using the built-in PHP json_encode function.

References

  • http://en.wikibooks/wiki/PHP_Programming/Data_Structures#The_Basics
  • http://en.wikipedia/wiki/Composite_type
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";
}
?>

You should create the data structure in php and echo it out with 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";
发布评论

评论列表(0)

  1. 暂无评论