2012-12-12 47 views
-1
$cnt = 0; 
while ($row = $result->fetch_assoc()) 
{ 
    $arre[$cnt]['id'] = $row['idevents']; 
    $arre[$cnt]['title'] = $row['title']; 
    $arre[$cnt]['start'] = "new Date(" . $row['start'] . "*1000)"; 
    $arre[$cnt]['end'] = "new Date(" . $row['end'] . "*1000)"; 
    $arre[$cnt]['allDay'] = $row['allday']; 
    $arre[$cnt]['url'] = $row['url']; 
    $cnt++; 
} 


$year = date('Y'); 
$month = date('m'); 

echo json_encode(array(

array(
    'id' => 111, 
    'title' => "Event1", 
    'start' => "$year-$month-10", 
    'url' => "http://yahoo.com/" 
), 

array(
    'id' => 222, 
    'title' => "Event2", 
    'start' => "$year-$month-20", 
    'end' => "$year-$month-22", 
    'url' => "http://yahoo.com/" 
) 

)); 

?> 

脚本底部的json_encode是一个示例。我需要获取$ arre和json_encode中的数据。 json_encode的格式将需要保持几乎完全相同,否则程序可能会发现它不可口,我的程序将无法工作。有谁知道什么是正确的代码技术在这里看起来像?关于使用PHP json_encode作为数组

谢谢!

+0

'json_encode'不能使它的JavaScript你,你的'新的Date()'的将不得不'eval'ed的JavaScript片面的。如果你需要它,你可能不得不手动创建你自己的并跳过'json_encode'。 – Wrikken

+2

请描述您使用上述代码所遇到的实际(特定)问题,以及您正在寻求哪些建议的相关建议。这个问题可能更适合[CodeReview.SE](http://codereview.stackexchange.com/) – DaveRandom

+2

也许我不明白,但为什么你不能只使用'json_encode($ arre)' – twiz

回答

1

如果您正在寻找使用json_encode()将数组返回给函数的正确格式,请继承一个示例。使用键值对访问不同的成员:

另外,使用关联数组,以便您可以通过其列的名称而不是整数值遍历客户端上的元素。

while ($row = $result->fetch_assoc()) 
{ 
    $thisRow = array(
        'id'  => $row['idevents'], 
        'title' => $row['title'], 
        'start' => date("F j, Y, g:i a", strtotime($row['start'])), 
        'end' => date("F j, Y, g:i a", strtotime($row['end'])), 
        'allDay' => $row['allday'], 
        'url' => $row['url'] 
    ); 
    array_push($arre, $thisRow); 
} 

return json_encode(
    array(
     "result" => "success", 
     "data" => $arre 
    ) 
); 

然后,在JavaScript/jQuery的:

$.post("myPost.php", post_data, 
    function(data) { 
     // store data.result; 
     // store data.data; 
    }, 
"json"); 
+0

这是最有帮助的。我非常期待应用这些策略。非常感谢你。 – Giuseppe

+0

另外,我不确定你在做什么2日期。如果您在原始文章中详细说明,我可以帮助您更新。在我上面的代码中,我只是将查询中的2个字符串格式化为标准日期格式。 – jamis0n