来自php的Jquery json数组

时间:2011-03-28 20:40:38

标签: php jquery multidimensional-array

我正在尝试重现以下内容,但我使用数据库中的行

var allCustomers = [

    { name: 'Customer1', contacts: [
                { name: 'Bob', id: ['1'] },
                { name: 'Sue', id: ['2'] },
                { name: 'John', id: ['3'] }
        ]},

    { name: 'Customer2', contacts: [
                { name: 'Max', id: ['4'] },
                { name: 'Ross', id: ['5'] },
                { name: 'Sally', id: ['6'] }
        ]}
];

在PHP中,我从数据库中获取行,每个客户都有多个联系人,这是我正在努力的方面。目前我正在使用以下方法:

<script type="text/javascript">
var allCustomers = [
<?php
include('connection.php');
$stmt = $db->prepare("SELECT customer.customerID, customerName, contactID, contactName  FROM customer INNER JOIN customerContact ON customer.customerID = customerContact.customerID");
if ($stmt->execute()) 
{
    while ($row = $stmt->fetch(PDO::FETCH_OBJ)) 
    {
            echo "{ name: '".$row->customerName."', contacts: [
                { name: '".$row->contactName."', id: ['".$row->contactID."'] }                
        ]},";
        }           
}       
?>    
];

但显然这不是一种非常巧妙的方式,只有当客户只有一个联系人时才会这样做,否则它会重现客户并再次联系。

你有什么建议解决这个问题,我可以使用php解码json函数或类似的东西吗?

感谢您的任何建议:)。

我正在尝试制作与this帖子类似的内容,但我需要将联系人的ID发回服务器。

3 个答案:

答案 0 :(得分:2)

这样的事情:

$data = array(
  array("name" => "Customer1", "contacts" => array(
    array("name" => "Bob", "id" => 1),
    array("name" => "Sue", "id" => 2),
    array("name" => "John", "id" => 3)
  )),
  array("name" => "Customer1", "contacts" => array(
    array("name" => "Max", "id" => 4),
    array("name" => "Ross", "id" => 5),
    array("name" => "Sally", "id" => 6)
  ))
);

echo json_encode($data);

回答提问者的评论:

$stmt = $db->prepare("SELECT customer.customerID, customerName, contactID, contactName  FROM customer INNER JOIN customerContact ON customer.customerID = customerContact.customerID");

$data = array();

if ($stmt->execute()) 
{
    while ($row = $stmt->fetch(PDO::FETCH_OBJ)) 
    {
        if (!isset($data[$row->customerId])
        {
            $data[$row->customerId] = array('name' => $row->customerName, 'contacts' => array());
        }

        $data[$row->customerId]['contacts'][] = array('name' => $row->contactName, 'id' => $row->contactId);
    }           
}   

echo json_encode(array_values($data));

答案 1 :(得分:0)

对于使用PHP创建JSON,您可以看到本教程:http://www.sencha.com/learn/Tutorial:Creating_JSON_Data_in_PHP

答案 2 :(得分:0)

做一切:

echo json_encode($array);