S
S
sorry_i_noob2018-03-26 23:26:00
PHP
sorry_i_noob, 2018-03-26 23:26:00

Php, when adding an element of the Model type to the array, 1 is added, and when a specific model field is added, the value is normal. Why is that?

Hello. There is this code:

class Model_Catalog extends ORM {
private function func2($category_id, $result_array) {
    $children = ORM::factory('Catalog')->where('catalog_id', '=', $category_id)->find_all()->as_array();
    if (count($children) > 0) {
      foreach ($children as $c) {
        $result_array[] += $c;
        $result_array += $this->func2($c->id, $result_array);
      }
    }
    return $result_array;
}
public function func1() {
    $all_elements = $this->func2($this->id, array());
    return $all_elements;
  }
}

Why is this line: $result_array[] += $c;adds one to $result_array? And if you write like this: $result_array[] += $c->id;, then it will add the id of the Catalog model instance. $result_array[] += $c;And if I write like this before : $test_value = $c;, then there will be an instance of the model in test_value. So why is a unit added to the array instead of a model instance? How can I fix this?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
sitalya, 2018-04-05
@sorry_i_noob

They tell you right ...
What you wrote:
Means:

$new_item = $new_item + $c;
//преобразуется в
//$new_item = NULL + object
//арифметическое сложение преобразует в
//$new_item = 0 + 1
//итог
//$new_item = 1;
$result_array[] = $new_item;

When you need it:
Read about the assignment operator and type conversions.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question