2017-04-13 69 views
-1

如何從我的API中提取每個JSON返回對象前面的id返回前面帶ID的JSON

電流:

{ 
    "1516":{ 
     "id":"1516", 
     "firstname":"Aluno", 
     "lastname":"Teste", 
     "email":"[email protected]", 
     "dlastaccess":"28-10-2016", 
     "coursename":"Curso Demonstra\u00e7\u00e3o" 
    } 
} 

我如何不想離開:

[ 
    { 
     "id":"1516", 
     "firstname":"Aluno", 
     "lastname":"Teste", 
     "email":"[email protected]", 
     "dlastaccess":"28-10-2016", 
     "coursename":"Curso Demonstra\u00e7\u00e3o" 
    } 
] 

我想這樣做,因爲我的清單模型不能正常工作的JSON返回來的路上,所以我無法檢查所有複選框。

API:

enter image description here

回答

1

這做工作:

$json = '{"1516":{"id":"1516","firstname":"Aluno","lastname":"Teste","email":"[email protected]","dlastaccess":"28-10-2016","coursename":"Curso Demonstra\u00e7\u00e3o"}}'; 

$values = json_decode($json, true); 

$values = array_values($values); 

echo json_encode($values); 

回報:

[{"id":"1516","firstname":"Aluno","lastname":"Teste","email":"[email protected]","dlastaccess":"28-10-2016","coursename":"Curso Demonstra\u00e7\u00e3o"}] 
+0

謝謝,它工作! :D –

+0

不客氣 – Sebastian

0

我猜你的$結果是一個數組(或物體)的本類型:

$ result [id] = array(sql retrieve);

因爲sql會返回結果列表,即使結果是唯一的。想象你的查詢返回了兩個結果,你怎麼能把它們分開?

嘗試:

回波json_encode($結果[$ cursoid])

回波json_encode($結果 - > $ cursoid)

0
$cursoid = $_GET['idcurso']; 

$sql = 'SELECT 
user2.id AS ID, 
user2.firstname AS Firstname, 
user2.lastname AS Lastname, 
user2.email AS Email, 
IF (user2.lastaccess = 0,"nunca", 
DATE_FORMAT(FROM_UNIXTIME(user2.1astaccess),"%d-96m-W")) AS dLastAccess ,c.fullname AS Coursename 
FROM mdl_user_enrolments AS ue 
JOIN mdl_enrol AS e ON e.id = ue.enrolid 
JOIN mdl_course AS c ON c.id = e.courseid 
JOIN mdl_user AS user2 ON user2 .id = ue.userid 
WHERE (SELECT timeaccess FROM mdl_user_lastaccess WHERE userid=user2.id AND courseid=c.id) IS NULL and c.id = ?'; 

$params = array($cursoid); 

$result = $DB->get_records_sql($sql, $params); 
echo json_encode(array_values($result)); // You can easily access array values without their keys by array_values(array $param) function 
0

使用array_values,默認php函數

$values = $DB->get_records_sql($sql, $params); 
$result = array_values($values); 
return json_encode($result);