PHP: Add new element to an array created from an object

Asked

Viewed 159 times

0

Hello, I have the following class in models/cliente.php:

<?php
class Cliente {
    public $id;
    public $nome;
    ...

    public function __construct($id, $nome, ...) {
        $this->id   = $id;
        $this->nome = $nome;
        ...
    }

    public static function all() {
        $list = [];
        $db = Db::getInstance();
        $req = $db->query("SELECT * FROM clientes");
        foreach($req->fetchAll() as $cliente) {
            $list[] = new Cliente($cliente['cliente_id'], $cliente['cliente_nome'], ...);
        }
        return $list;
    }

    ...
}
?>

And I’d like to know how to add a new element to $list[], which will be obtained from the modified SQL query as below:

...

$req = $db->query("SELECT clientes.*, shoppings.shopping_nome FROM clientes, shoppings WHERE clientes.shopping_id = shoppings.shopping_id");

...

I tried to do it this way:

...

$list[] = new Cliente($cliente['cliente_id'], ...);
$list[] = $cliente['shopping_nome'];

...

But it didn’t work.

Thank you in advance.


controllers/clientes_controller.php:

<?php
class ClientesController {
    public function show() {
        $clientes = Cliente::all();
    }

    ...
}

views/clientes/show.php:

<?php
foreach ($clientes as $cliente) {
    echo $cliente->id;
    echo $cliente->nome;
    ...
    echo $cliente->shopping_nome; // Poderia usar assim?
}
?>

1 answer

0


From what I understand, you don’t want to add a property called shopping_nome in your class Cliente, right?

Then you can add a variable called $key in the loop to get the iteration index.

public static function all()
{
    $list = [];
    $db = Db::getInstance();
    $req = $db->query("SELECT clientes.*, shoppings.shopping_nome FROM clientes, shoppings WHERE clientes.shopping_id = shoppings.shopping_id");
    foreach($req->fetchAll() as $key => $cliente) {
        $list[$key] = new Cliente($cliente['cliente_id'], $cliente['cliente_nome'], ...);
        $list[$key]->shopping_nome = $cliente['shopping_nome'];
    }

    return $list;
}
  • 1

    That’s exactly what I wanted to do. Solution so simple. Thanks even, man!

  • Give nothing! I’m happy to help you.

Browser other questions tagged

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