javascript - Yii 为 JavaScript 编码数组

标签 javascript php arrays yii

我需要用例如编码一个多维数组CJavaScript 或 CJSON,但我需要避免使用 PHP 数组键。

假设数据结构如下

$dataTree = array(
  '39'=>array(
      'label' => 'node1',
      'children' => array(
          '42'=>array('label' => 'child1'),
          '44'=>array('label' => 'child2'),
      ),
  ),
  '40'=>array(
      'label' => 'node2',
  )
);

我需要获得以下输出(在 Javascript 中):

var data = [
    {
        label: 'node1',
        children: [
            { label: 'child1' },
            { label: 'child2' }
        ]
    },
    {
        label: 'node2',
        children: [
            { label: 'child3' }
        ]
    }
];

有什么办法吗?

最佳答案

使用此代码。

<?php
$dataTree = array(
  '39'=>array(
      'label' => 'node1',
      'children' => array(
          '42'=>array('label' => 'child1'),
          '44'=>array('label' => 'child2'),
      ),
  ),
  '40'=>array(
      'label' => 'node2',
     'children' => array(
          '42'=>array('label' => 'child3'),         
      ),
  )
);
$res = array();
foreach( $dataTree as $val) 
{
   $temp_ch = array();
  foreach($val["children"] as $ch)
    $temp_ch[]=$ch; 
  $val["children"] = $temp_ch;
$res[] = $val;
}
echo json_encode($res); 


?>

关于javascript - Yii 为 JavaScript 编码数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20718485/

相关文章:

javascript - WinJS 渲染 listview 时捕获事件

php - 在 Laravel 5.3 Blade 中渲染动态 anchor 标记

java - 如何在字符串上突出显示

Javascript - 从 JSON 数组中删除对象

javascript - Protractor 未检测到弹出对话框(md-dialog-content)

javascript - 如何在 Node.JS 中使用 gmail API 创建带有附件的草稿消息?

php - 以特定方式显示数组元素

php - 排序线程/嵌套注释 - PHP

php - 数组数组到对象数组 php

javascript ->>= 是什么意思?