array of simple arrays for json_encode

4

I need to create a json document, with the following structure:

[
{
    "Name": "Lacy",
    "Email": "[email protected]"
},
{
    "Name": "Chancellor",
    "Email": "[email protected]"
}]

Currently, I have the following array:

array (size=10)
  0 => 
    array (size=3)
      'id' => string '1' (length=1)
      'nome' => string 'Lacy' (length=35)
      'email' => string '[email protected]' (length=20)
  1 => 
    array (size=3)
      'id' => string '2' (length=1)
      'nome' => string 'Chancellor' (length=25)
      'email' => string '[email protected]' (length=25)

And to try to turn it into the result I want, I have the following code:

$arrayClientes = array();

for($i=0; $i<count($clientes); $i++){
    array_push($arrayClientes, array("Nome"=>$clientes[$i]['nome'], "Email" => $clientes[$i]['email']));
}

echo '<pre>';
echo json_encode($arrayClientes);
echo '<pre>';

In this way, it does not echo of $arrayClientes .

How can I create a Json array like that?

    
asked by anonymous 20.02.2015 / 22:42

2 answers

1

I believe this is what you need, just adapt it a bit:

$array = [
    0 => ['id' => 1, 'nome' => 'teste', 'email' => 'email'],
    1 => ['id' => 2, 'nome' => 'teste2', 'email' => 'email2'],
    2 => ['id' => 3, 'nome' => 'teste3', 'email' => 'email3']
];
var_dump($array); //teste

//Percorre todo o array, passando ele mesmo por referência para a função e removendo seu índice 'id'. 
//Assim permanecendo somente o que você precisa;
array_filter($array, function(&$array) {
    unset($array['id']);
});
var_dump($array); //teste

echo json_encode($array);
    
20.02.2015 / 23:04
1

So it also solves:

$arrayClientes = array();

if (count($clientes))    
    foreach ($clientes as $cliente) {
        $arrayClientes[] = array(
                         "Name"  => $cliente['nome'],
                         "Email" => $cliente['email']
        );
    }

    echo '<pre>';
    echo json_encode($arrayClientes);
    echo '<pre>';
    
06.04.2016 / 22:30