Unable to unzip array with string keys

FATAL ERROR Uncaught Error: Unable to unzip array with string keys

I know that I can just run the fetch() method twice and pass in ['q'] and ['bind'] , but I'm trying to figure out how to use the new ones ... to unpack the values. I want to pass the values ​​as follows:

 (string) SQL, (Array) Bind Values 

But I think he is trying to unpack an array of binding values, as well as an array of responses from the fetch() method. Is it possible to unpack this array (it looks something like this :)

 array(2) { ["q"]=> string(7) "example" ["bind"]=> array(1) { ["example"]=> string(3) "one" } } 

This is all the code, in case you need to see how it all fits together:

 class ModelController { public static function execute($sql, $vals) { var_dump($vals); } } class ModelContainer { private $queries = []; public function add_model(Model $model, $name) { $this->queries[$name] = $model; return $this; } public function exec_all() { foreach($this->queries as $q) { ModelController::execute(...$q->fetch()); } } public function exec($name) { } } class Model { private $sql; private $vals = []; public function set_q($statement) { $this->sql = $statement; return $this; } public function bind($vals = []) { $this->vals = $vals; return $this; } public function fetch() { return ['q' => (string)$this->sql, 'bind' => $this->vals ]; } } $m = new ModelContainer(); $m->add_model((new Model)->set_q('example sql here')->bind(['example' => 'example value here']), 'one'); $m->exec_all(); 
+5
source share
2 answers

The problem is that the "splat" operator (the operator of unpacking an array or ... ) does not work with associative arrays. Example:

 $array = [ 1,2,3 ]; $assoc = [ "one" => 1, "two" => 2, "three" , 3 ]; var_dump(...$array); //Works var_dump(...$assoc); //Doesn't work 

You need to force the array to be indexed numerically in order to unpack it. You do this with array_values :

 $values = array_values($q->fetch()); ModelController::execute(...$values); 

Array values ​​ensure that all values ​​have a serial number key.

+11
source

I had the same problem trying to give the Mailer $ user method.

 $userMailer = new UserMailer(); $userMailer->send('welcome', [$user]); 

Including user $ in a new array should fix this.

0
source

Source: https://habr.com/ru/post/1259929/


All Articles