D
D
DeniSidorenko2020-05-16 13:50:50
PHP
DeniSidorenko, 2020-05-16 13:50:50

How to check by key?

Good afternoon, there is such an array in php

array(2) {
  [0]=>
  array(4) {
    ["category_id"]=>
    string(3) "137"
    ["name"]=>
    string(49) "Лента термоуплотнительная"
    ["children"]=>
    array(0) {
    }
    ["href"]=>
    string(90) "http://site/index.php?route=product/category&path=1_134_135_136_137"
  }
  [1]=>
  array(4) {
    ["category_id"]=>
    string(3) "138"
    ["name"]=>
    string(89) "Огнезащита для воздуховодов с применением матов"
    ["children"]=>
    array(0) {
    }
    ["href"]=>
    string(90) "http://site.ru/index.php?route=product/category&path=1_134_135_136_138"
  }
}


Each array is another array with keys. The array itself above is in a variable. The question is, how can I check that if at least one element of the children array is not empty, then execute one function. That is, in the example above, children are empty everywhere, but if at least somewhere there is ['children'] =>array (1) then fulfill the conditions. Thanks in advance

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
Roman Sarvarov, 2020-05-16
@megakor

$array = [/* ... */];

if (arrHasChildren($array)) {
    // doSomeThing();
}

function arrHasChildren(array $array): bool
{
    foreach ($array as $value) {
        if (!empty($value['children'])) {
            return true;
        }
    }

    return false;
}

A
Alex, 2020-05-16
@Kozack

Offhand, something like this:

function array_any(array $array, callable $fn) {
    foreach ($array as $value) {
        if($fn($value)) {
            return true;
        }
    }
    return false;
}

array_any($arr, function ($i) { return !empty($i['children']) }) // true || false

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question