Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Code:</p> <pre><code>function search($array, $key, $value) { $results = array(); if (is_array($array)) { if (isset($array[$key]) &amp;&amp; $array[$key] == $value) { $results[] = $array; } foreach ($array as $subarray) { $results = array_merge($results, search($subarray, $key, $value)); } } return $results; } $arr = array(0 =&gt; array(id=&gt;1,name=&gt;"cat 1"), 1 =&gt; array(id=&gt;2,name=&gt;"cat 2"), 2 =&gt; array(id=&gt;3,name=&gt;"cat 1")); print_r(search($arr, 'name', 'cat 1')); </code></pre> <p>Output:</p> <pre><code>Array ( [0] =&gt; Array ( [id] =&gt; 1 [name] =&gt; cat 1 ) [1] =&gt; Array ( [id] =&gt; 3 [name] =&gt; cat 1 ) ) </code></pre> <p>If efficiency is important you could write it so all the recursive calls store their results in the same temporary <code>$results</code> array rather than merging arrays together, like so:</p> <pre><code>function search($array, $key, $value) { $results = array(); search_r($array, $key, $value, $results); return $results; } function search_r($array, $key, $value, &amp;$results) { if (!is_array($array)) { return; } if (isset($array[$key]) &amp;&amp; $array[$key] == $value) { $results[] = $array; } foreach ($array as $subarray) { search_r($subarray, $key, $value, $results); } } </code></pre> <p>The key there is that <code>search_r</code> takes its fourth parameter by reference rather than by value; the ampersand <code>&amp;</code> is crucial.</p> <p>FYI: If you have an older version of PHP then you have to specify the pass-by-reference part in the <em>call</em> to <code>search_r</code> rather than in its declaration. That is, the last line becomes <code>search_r($subarray, $key, $value, &amp;$results)</code>.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload