![](/img/trans.png)
[英]How To Create PHP Array to JSON Array using json_encode();
[英]PHP Array to JSON Array using json_encode() and how can json parse android;
我有一个php数组,并使用json_encode($ arr)对其进行编码。
我想使用JSONObject在Android中解析此Json。
但是我怎么解析它,并只在text_view上打印名称,如Rohan(所有名称)在text_view上打印。
[["Rohan","example1.com"],["Ashok","example2.com"]]
我可以把它转换成这样吗
{ "students": [{"Rohan":"example1.com"}]
}
首先,让我们这样命名数组:
编辑
在实际执行编码之前,最好添加一个标头指定内容类型:
header('Content-type: application/json')
json_encode(array('students' => $arr));
这样,您将获得以下信息:
{ "students": [{"Rohan":"example1.com"}]}
而不是您现在正在得到什么。
要从Android中的JSONObject获取名称,您需要循环遍历该数组,然后一一挑选。 假设您以字符串形式获取JSON形式的PHP,则可以尝试如下操作:
JSONObject jsonObject = new JSONObject(mJSON);
JSONArray jsonArray = jsonObject.getJSONArray("students");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject current = jsonArray.getJSONObject(i);
if (!current.getString("student_name").isEmpty()) {
mTextView.setText(current.getString("student_name"));
}
}
希望能有所帮助。
您可以尝试以这种方式用php对json进行编码以满足您的需求:
<?php
$json='{
"students": [
{
"Rohan": "example1.com"
},
{
"Ashok":"example2.com"
}
]
}';
var_dump($json);
$students=array(
"student"=>array(
array("Rohan"=>"example1.com"),
array("Ashok"=>"example2.com")
)
);
var_dump(json_encode($students, JSON_PRETTY_PRINT));
但是我认为以这种方式这样做有点奇怪,因为您必须创建仅包含一个键的数组。 我认为Herrmartell架构更加清晰。 干杯!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.