Post 1:N (one customer many phonenumbers) JSON Array to android and parse it in PHP

504

I want to create a more complex JSON Array where a customer (which has a name) has many phonenumbers so that i can parse it in PHP and i need your help.

i.e.:

public Class ContactVO
{
    public String diplayname;
    public ArrayList<PhoneVO> phonenumbers = new ArrayList<PhoneVO>();
}


public Class PhoneVO
{
    public String number;
}

Can s.o. give me an example how to create the above 1:N structure as JSON Array and how to parse it via PHP?

I put everything in a ArrayList and added the GSON library to may project.

The result is:

[
  {"contact_id":"1","displayname":"Bjyyyyy","phonenumbers":[{"number":"066-6228"}]},  
  {"contact_id":"2","displayname":"Rainer Unsinn","phonenumbers":[{"number":"(066) 214-52"}]},
  {"contact_id":"3","displayname":"Dieter karpenstein","phonenumbers":[{"number":"06621716669"}]},
  {"contact_id":"4","displayname":"Sido","phonenumbers":[{"number":"(085) 011-1555"}]},
  {"contact_id":"5","displayname":"Jochen Müller","phonenumbers":[{"number":"01773313261"}]}
]

How should the receiving PHP File lookslike to parse that?

696

Answer

Solution:

Are you just looking for the json_decode function?

$fromPost = $_POST['contact'];
$object = json_decode($fromPost, true); // Read the doc to decide whether you want the "true" or not
var_dump($object);

Edit: You could have something like that (not tested)

$string = '[
  {"contact_id":"1","displayname":"Bjyyyyy","phonenumbers":[{"number":"066-6228"}]},  
  {"contact_id":"2","displayname":"Rainer Unsinn","phonenumbers":[{"number":"(066) 214-52"}]},
  {"contact_id":"3","displayname":"Dieter karpenstein","phonenumbers":[{"number":"06621716669"}]},
  {"contact_id":"4","displayname":"Sido","phonenumbers":[{"number":"(085) 011-1555"}]},
  {"contact_id":"5","displayname":"Jochen Müller","phonenumbers":[{"number":"01773313261"}]}
]';

$decoded = json_decode($string);

foreach($decoded as $person) {
        echo $person['displayname'] . "\n";
        foreach($person['phonenumbers'] as $phone) {
                echo $phone['number'] . "\n";
        }
}

People are also looking for solutions to the problem: php - MySQL INSERT INTO doesn't do anything - not even error

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.