php помещает массив из _construct в функцию

Я использую API и мне было интересно, почему у меня проблемы с получением массива для перехода в функцию. Следующее работает нормально, но как я могу заставить его работать для массива.

public function __construct()
{
parent::__construct(); // Init parent constructor
$this->dbConnect();
$this->test();
}

public function test()
{
$this->category = "bracelets";

}

private function piece()
{
// Pass an array into this function here and then use depending on array key
$cat = $this->category;
}

Поэтому вместо константных браслетов $ this-> category = «. Я бы хотел, чтобы это был массив. Например,

public function test()
{
$array = [
"foo" => "bar",
"bar" => "foo",
];
$this->category = $array;

}

Хорошо, это было решено. Это было из-за незначительной ошибки в другом месте. На мгновение я поверил, что существует проблема с массивами в спокойном API.

Я надеюсь, что это полезно для любых других, кто хочет передать результаты одной функции другому в классе API.

-1

Решение

Глядя на ваш код, кажется, вы хотите category свойство быть array всех категорий читать из базы данных ..?

Я обнаружил некоторые ошибки в вашем коде:

  • У вас есть смешанные имена переменных на $cat_array против $cat_arr
  • Вы выбираете cat столбец из БД, но попробуйте прочитать category

Я сделал небольшие изменения в вашем test() способ исправить это:

public function __construct()
{
parent::__construct(); // Init parent constructor
$this->dbConnect();
$this->test();
}

// Array with name of all categories, indexed by category id
private $category;

public function test()
{
$query = "SELECT c.id, c.cat FROM category c order by c.id asc";
$cat = $this->mysqli->query($query)
or die ($this->mysqli->error . __LINE__);

if ($cat->num_rows > 0) {
$cat_array = array();
while ($crow = $cat->fetch_assoc()) {
$id = $crow['id'];
$cat_array[$id] = $crow['cat'];
//$cat_array[$crow['id']]=$crow['category'];
}
$this->category = $cat_array;
//$this->response($this->json($result), 200); // send  details
}
}

private function piece()
{
// Pass an array into this function here and then use depending on array key
$cat = $this->category;

// Check if it is working as expected
print_r($cat);
}
0

Другие решения

Других решений пока нет …

По вопросам рекламы ammmcru@yandex.ru
Adblock
detector