0

I have this array

Array
(
    [0] => Array
        (
            [id] => 15
            [parent] => #
            [text] => Shb2-1
        )

    [1] => Array
        (
            [id] => 17
            [parent] => 16
            [text] => Shb2-3
        )

    [2] => Array
        (
            [id] => 18
            [parent] => 17
            [text] => Shb2-4
        )

)

I would like to search if [parent] value exist in the same array as [id]

If it do not exist exists, then the [parent] value will be replaced to 0.

Example:

check if the value 16 exists in the whole array as [id] (in my example available [id] are 15, 17 and 18).

if it do not exist, 16 will be replaced by 0. Then check for the next array key, and so until I get un output with final replaced values.

Thank you for your help.

Cartha
  • 11
  • 5

1 Answers1

0

If you wanted to change parent to zero if it is not equal to any id, then I think this simple code will do it:

foreach ($array as $key => $val) {
    // Search if 'id' exists in the array
    $a_key = array_search($val['parent'], array_column($array, 'id'));
    // Check if 'id' is in the array, if not then replace 'parent' with 0
    if ($a_key == false) $array[$key]['parent'] = '0';
}
Sayed
  • 1,022
  • 3
  • 12
  • 27