0

I'm trying create a JSON Array using PHP. But I want this JSON receive a master key like this: cidades:[{"id":"1", "nome":"Guaira"}] and when I try create its only create [{"id":"1","cidade":"Guaira"}].

How can I do it ?

<?php
include '../objetos/Cidade.php';
include '../dao/CidadeDAO.php';

if($_GET['action'] == 'getCidades'){
    $idEstado = $_GET['idEstado'];  

    $dao = new CidadeDAO();
    $lista = $dao->getCidadeByEstado($idEstado);


    $arr = array();
    foreach ($lista as $object){
        $result = array("id" => $object['id'], "cidade" => $object['cidade']);
        array_push($arr, $result);
    }   

    echo json_encode($arr);

//output: [{"id":"1","cidade":"Guaira"},{"id":"1","cidade":"Barretos"}] }

?>
1
  • change $result with $result["cidades"][] Commented Feb 18, 2015 at 13:21

2 Answers 2

2

Create a top-level array with key 'cidades' and put your data into :

$arr = array('cidades' => array());
foreach ($lista as $object){
    $result = array("id" => $object['id'], "cidade" => $object['cidade']);
    array_push($arr['cidades'], $result);
}   
Sign up to request clarification or add additional context in comments.

Comments

1

Try this:

$arr["cidades"] = array();
array_push($arr["cidades"], $result);

This code produces a JSON formatted data with a key named "cidades" attached to it so that something like cidades:[{"id":"1", "nome":"Guaira"}] is produced. For clarity check out this.

4 Comments

Why should the OP "try this"? Please explain to the OP (and future visitors to SO) why you did what you did.
The code is simple...it produces a Json formatted data with a key named "cidades" attached to it so that something like cidades:[{"id":"1", "nome":"Guaira"}] is produced. For clarity check out androidhive.info/2012/05/how-to-connect-android-with-php-mysql
Thanks I am just a newbie...didn't know
Please don't recommend Android Hive; that tutorial (and several others on the same site) contain serious SQL injection vulnerabilities. See more here.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.