这是我的代码:
function get_roles(){
$role = array("1"=>"user management", "2"=>"create", "3"=>"update","4"=>"publish", "5"=>"delete", "6"=>"image upload", "7"=>"advertisement", "8"=>"department", "9"=>"category", "10"=>"sub category", "11"=>"grievance", "12"=>"feedback", "13"=>"help");
foreach($role as $x => $x_value) {
$result= $x_value;
}
return $result;
}
echo get_roles();
我想在php中将所有值作为json返回。但它只返回最后一个值。怎么做?是否可以返回所有值?
答案 0 :(得分:1)
使用json_encode返回json字符串,如下所示:
return json_encode($role);
如果您希望索引从0开始,请使用return json_encode(array_values($role));
答案 1 :(得分:1)
您需要为数组创建数组添加角色元素。
function get_roles(){
$roles = array();
$role = array("1"=>"user management", "2"=>"create", "3"=>"update","4"=>"publish", "5"=>"delete", "6"=>"image upload", "7"=>"advertisement", "8"=>"department", "9"=>"category", "10"=>"sub category", "11"=>"grievance", "12"=>"feedback", "13"=>"help");
foreach($role as $x => $x_value) {
$roles[] = $x_value;
}
return json_encode($roles);
}
echo get_roles();
答案 2 :(得分:0)
请使用json_encode()
function get_roles(){
$role = array("1"=>"user management", "2"=>"create", "3"=>"update","4"=>"publish", "5"=>"delete", "6"=>"image upload", "7"=>"advertisement", "8"=>"department", "9"=>"category", "10"=>"sub category", "11"=>"grievance", "12"=>"feedback", "13"=>"help");
return json_encode($role);
}
$getresult = get_roles();
echo $getresult;
答案 3 :(得分:0)
<?php
function get_roles(){
$role = array("1"=>"user management", "2"=>"create", "3"=>"update","4"=>"publish", "5"=>"delete", "6"=>"image upload", "7"=>"advertisement", "8"=>"department", "9"=>"category", "10"=>"sub category", "11"=>"grievance", "12"=>"feedback", "13"=>"help");
foreach($role as $x => $x_value) {
return json_encode($role);
}
}
print_r(get_roles());