我的功能如下,以及它的输出。
$results = mysql_query("SELECT * FROM tmsessions WHERE session_user_id ='".$_SESSION['user_id']."'");
$count = mysql_num_rows($results);
$username = mysql_fetch_assoc(mysql_query("SELECT user_fname FROM tmusers WHERE user_id = '".$_SESSION['user_id']."'"));
$json_data = array( 'userID'=>$_SESSION['user_id'], 'userName'=>$username['user_fname'], 'total'=>$count );
while($session = mysql_fetch_assoc($results))
{
$numListItems = mysql_num_rows(mysql_query("SELECT session_id, listing_unique_id FROM tmdata WHERE session_id = '".$session['session_id']."'"));
$listItems = array('sessionID'=>$session['session_id'],
'sessionName'=>$session['session_name'],
'sessionCount'=>$numListItems,
'sessionDC'=>date('h:iA - M m y',strtotime($session['session_date_created'])),
'sessionDM'=>date('h:iA - M m y',strtotime($session['session_date_modified'])),
'sessionActive'=>$session['session_active']);
array_push($json_data, $listItems);
}
return json_encode($json_data);
哪些外出:
{"0":
{"sessionID":"9",
"sessionName":"dataName0",
"sessionCount":100,
"sessionDC":"12:11AM - Jun 06 11",
"sessionDM":"01:00AM - Jan 01 70",
"sessionActive":"1"},
"1":
{"sessionID":"10",
"sessionName":"dataName1",
"sessionCount":100,
"sessionDC":"05:04PM - Jun 06 11",
"sessionDM":"01:00AM - Jan 01 70",
"sessionActive":"1"},
"userID":"1",
"userName":"Ezra",
"total":2}
我需要“0”:和“1”:位成为“listItem”:每个新的关联数组,但我不知道如何正确操作数组来获得它:(。
答案 0 :(得分:1)
在PHP中,索引和关联数组被处理为相同的类型(即矩阵或一维数组,a [0],a [1],... a [N],vs a ['one'] ,a ['two'],... a ['something'])。
使用array_push()时,您不是在创建或添加关联哈希,而是在数组末尾创建索引值。
您可以使用您选择的名称直接分配,而不是使用array_push()函数,例如
$listItems[$session['session_id']] = array('sessionID'=>$session['session_id'],
'sessionName'=>$session['session_name'],
'sessionCount'=>$numListItems,
'sessionDC'=>date('h:iA - M m y',strtotime($session['session_date_created'])),
'sessionDM'=>date('h:iA - M m y',strtotime($session['session_date_modified'])),
'sessionActive'=>$session['session_active']);
答案 1 :(得分:1)
如果我正确理解你的问题,请尝试这个,而不是对不起,请告诉我我的理解错误?
$results = mysql_query("SELECT * FROM tmsessions WHERE session_user_id ='".$_SESSION['user_id']."'");
$count = mysql_num_rows($results);
$username = mysql_fetch_assoc(mysql_query("SELECT user_fname FROM tmusers WHERE user_id = '".$_SESSION['user_id']."'"));
$json_data = array( 'userID'=>$_SESSION['user_id'], 'userName'=>$username['user_fname'], 'total'=>$count );
while($session = mysql_fetch_assoc($results))
{
$numListItems = mysql_num_rows(mysql_query("SELECT session_id, listing_unique_id FROM tmdata WHERE session_id = '".$session['session_id']."'"));
$listItems = array('sessionID'=>$session['session_id'],
'sessionName'=>$session['session_name'],
'sessionCount'=>$numListItems,
'sessionDC'=>date('h:iA - M m y',strtotime($session['session_date_created'])),
'sessionDM'=>date('h:iA - M m y',strtotime($session['session_date_modified'])),
'sessionActive'=>$session['session_active']);
$json_data['listItem'][] = $listItems;
}
return json_encode($json_data);