-1

I have two of these methods. The get_value_from_raw_data method, if found by the key, should return a value, but it always returns false.

public function get_value_from_raw_data($associative_key , $haystack) {

    foreach ($haystack as $key => $value) {
        if (! is_array($value)) {
            if ($key === $associative_key) {
                return $value;
            }   else {
                continue;
            }
        }   else if (is_array($value)) {
            $this->get_value_from_raw_data($associative_key , $haystack[$key]);
        }
    }

    return false;
}

private function convert_value($value) {

    $new_value = $this->get_value_from_raw_data($value['associative_key'] , $this->raw_data);

    if ($value['path_to'] !== "") {
        $paths = explode('.' , $value['path_to']);

        $temp = &$this->used_model;
        foreach ($paths as $key) {
            $temp = &$temp[$key];
        }

        $temp[$value['key_name']] = $new_value;
    }   else {
        $this->used_model[$value['key_name']] = $new_value;
    }
}

Also, if I use dd inside this method before return, then it displays the value, and after return it is already gone.

enter image description here

  • It looks like the return value depends on `$this->raw_data`, could you include a bit of what that variable looks like? The structure of that variable is maybe an array fully consisting of subarrays, so that the condition `!is_array()` never holds. – user228395 Nov 16 '19 at 21:10
  • If you are looking for a specific key in a multidimensional array - you may want to look at [`array_walk_recursive()`](https://www.php.net/manual/en/function.array-walk-recursive.php) – Nigel Ren Nov 16 '19 at 21:14
  • @NigelRen, thanks for the answer, but I'm not sure if this option suits me. – Василий Пупкин Nov 16 '19 at 21:22

1 Answers1

0

You're not returning the value when you make a recursive call to the function:

else if (is_array($value)) {
    $this->get_value_from_raw_data($associative_key , $haystack[$key]);
}

should be:

else if (is_array($value)) {
    return $this->get_value_from_raw_data($associative_key , $haystack[$key]);
}
Nick
  • 138,499
  • 22
  • 57
  • 95
  • Thanks. Why is this happening? – Василий Пупкин Nov 16 '19 at 21:08
  • @ВасилийПупкин when you go to deeper levels in the array you are eventually returning the value (`return $value`) but when you make a recursive call you are not returning the value, so your code simply exits the loop and hits the `return false` statement – Nick Nov 16 '19 at 21:11
  • I'm understood, thank you again. Although I thought that he should sooner or later stumble on the first condition and just do return $value. – Василий Пупкин Nov 16 '19 at 21:16
  • @ВасилийПупкин it will, but you then have to return that value from the recursive call as well. – Nick Nov 16 '19 at 21:17