simple array arrays for json_encode

Asked

Viewed 10,740 times

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>';

This way, he doesn’t do the echo of $arrayClientes.

How can I create a Json array like those?

  • I already solved it. The problem was not in the array, but in the data it received. I had to make utf8_encode to the name that came in the array.

2 answers

2

Thus also resolves:

$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>';

1

I believe that’s what you need, just adapt a little:

$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);
  • Good Raphael, your code works. The problem I’m having now is with parentheses.. How do I convert my array to straight parentheses ? because my array comes from an aql query

  • Where exactly does this problem happen?

  • In SQL, are you receiving your data as an object? How Array? @user3587262

  • Yes, the array I present and what I receive

  • @user3587262, good to see now that you’ve solved...

Browser other questions tagged

You are not signed in. Login or sign up in order to post.