-1

II'm using an API and was wondering why I am having trouble getting an array to cross into a function. The following works fine but how can I make it work for an array.

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

So instead of a constant $this->category="bracelets. I would like this to be an array. e.g.

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

}

Ok, this has been resolved. It was due to a minor error elsewhere. For a moment I believed there was an issue with arrays in a restful API.

I hope this is useful to any others who wish to pass one function results to another in an api class.

martyn
  • 230
  • 5
  • 22
  • 2
    And what's the problem? What's wrong with your code? – MegaAppBear Mar 03 '15 at 17:29
  • Arrays should work the same way as strings here. There's no additional "trick" to assign an array to a property and use it from there. It's unclear what your issue is. – deceze Mar 04 '15 at 10:17

1 Answers1

0

Looking at you code, it seems you want the category property to be an array of all categories, read from the database..?

I did spot some bugs in your code:

  • You have variable name mixups on $cat_array vs. $cat_arr
  • You select cat column from DB but try read category

I have made slight changes in your test() method to fix it:

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);
}
mhall
  • 3,671
  • 3
  • 23
  • 35