0

我正在开发一个包含 java 文件和 php 文件的应用程序。java 文件调用 php 文件,这些文件在 ddbb 中执行查询并将结果作为数组 php 返回,但将其打印在屏幕上。我在java中把它当作一个字符串,我必须将它转换为数组或集合,但我不知道该怎么做。

php 打印的结果示例如下:

Array
(
[0] => Array
    (
        [id] => 1
        [0] => 1
        [name] => pepe
        [1] => pepe
    )

[1] => Array
    (
        [id] => 2
        [0] => 2
        [name] => antoñito
        [1] => antoñito
    )

[2] => Array
    (
        [id] => 3
        [0] => 3
        [name] => loló
        [1] => loló
    )

[3] => Array
    (
        [id] => 4
        [0] => 4
        [name] => ñoño
        [1] => ñoño
    )

[4] => Array
    (
        [id] => 5
        [0] => 5
        [name] => Antoñito
        [1] => Antoñito
    )

[5] => Array
    (
        [id] => 7
        [0] => 7
        [name] => José
        [1] => José
    )

)

如果我使用 json_encode($the_array) 这是结果:

[{"id":"1","0":"1","name":"pepe","1":"pepe"},    {"id":"2","0":"2","name":"anto\u00f1ito","1":"anto\u00f1ito"},{"id":"3","0":"3","name":"lol\u00f3","1":"lol\u00f3"},{"id":"4","0":"4","name":"\u00f1o\u00f1o","1":"\u00f1o\u00f1o"},{"id":"5","0":"5","name":"Anto\u00f1ito","1":"Anto\u00f1ito"},{"id":"7","0":"7","name":"Jos\u00e9","1":"Jos\u00e9"}]

谢谢大家

4

3 回答 3

5

您应该为您的数据选择一种序列化方法。例如 XML、Protocol Buffers或 JSON。

我个人建议您使用 JSON,因为它轻量级,即使对人类来说也易于阅读,并且有多种库可供两种语言使用。

PHP端的编码

$encoded = json_encode($data);

使用 Jackson 在 Java 端解码

final ObjectMapper objectMapper = new ObjectMapper();
// the better way is to create a custom class with the correct format
final Map<?, ?> decoded = objectMapper.readValue(encoded, Map.class);
于 2012-06-19T08:58:18.780 回答
2

使用一些更标准化的传输格式,例如 JSON。PHP 端必须使用对数组进行编码,json_encode()而 Java 端需要一些库来对其进行解码(请参阅相关问题)。

于 2012-06-19T08:57:13.283 回答