I am developing an app that has java files and php files. The java files call to the php files, these execute queries in the ddbb and return the result as an array php, but printing it in the screen. I take this in java like an string, and I have to convert it to and array or collection, but I have no idea how to do it.
An example of the result that php prints is:
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é
)
)
If I use json_encode($the_array) this is the result:
[{"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"}]
Thanks everyone
-
What have you tried?Oliver Charlesworth– Oliver Charlesworth2012年06月19日 08:54:42 +00:00Commented Jun 19, 2012 at 8:54
-
1use an interchange format like xml or json.Rufinus– Rufinus2012年06月19日 08:55:50 +00:00Commented Jun 19, 2012 at 8:55
-
1the best idea would be to think about your design. Passing arrays AS STRING from PHP to Java. Calling PHP from Java to do database access? All of this sounds quite horrible to me.gexicide– gexicide2012年06月19日 08:58:48 +00:00Commented Jun 19, 2012 at 8:58
3 Answers 3
You should select a serialization method for your data. For e.g. XML, Protocol Buffers, or JSON.
I recommend you use JSON because it's lightweight, easy to read even for humans and there are broad libraries available for both languages.
Encoding on the PHP side
$encoded = json_encode($data);
Decoding on the Java side with Jackson
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);
4 Comments
json_decode().Use some more standardized transport format, like JSON. PHP side has to encode the array using json_encode() and Java side needs some library to decode it (see relevant question).
Comments
I think that this can be useful http://publib.boulder.ibm.com/infocenter/wsmashin/v1r1/index.jsp?topic=/com.ibm.websphere.sMash.doc/using/zero.php/TypeConversion.html
Comments
Explore related questions
See similar questions with these tags.