Problem with recursive function in array

1

I have a function (which I found here in the forum) that does a search in the array and returns if it has the value that I search or not, so far so good. Only a need arose, I need to return the position number he found, as it returns only -1, so I know what value was not found. So I would like it to return to me which position of the array it found the value. Since I do not have much experience yet, I could not edit the code to do this. Follow the code.

function search($haystack, $needle, $index = NULL) {

 if (is_null($haystack)) {
    return -1;
  }

$arrayIterator = new \RecursiveArrayIterator($haystack);

$iterator = new \RecursiveIteratorIterator($arrayIterator);

while ($iterator->valid()) {

    if (( ( isset($index) and ( $iterator->key() == $index ) ) or ( !isset($index) ) ) and ( $iterator->current() == $needle )) {

        return $arrayIterator->key();
    }

    $iterator->next();
  }

   return -1;
}

Usage

$arrayBanco = returnBanco();
echo search($arrayBanco, $cnpj, 'CNPJ');

Structure of my array

Array
(
[1] => Array
    (
        [CNPJ] => 02814497000700
        [SERIE] => 1
        [NOTA] => 000245924
    )

[2] => Array
    (
        [CNPJ] => 05651966000617
        [SERIE] => 1
        [NOTA] => 000365158
    )

[3] => Array
    (
        [CNPJ] => 05651966000617
        [SERIE] => 1
        [NOTA] => 000365645
    )

[4] => Array
    (
        [CNPJ] => 05651966000617
        [SERIE] => 1
        [NOTA] => 000365946
    )

)

    
asked by anonymous 05.01.2017 / 14:07

2 answers

2

You can use the array_search function to return the value of the array key:

$key = array_search('conteudo a ser buscado', $array);

Follow php Reference: link

Edition: In this Multidimensional case, you can do this:

<?php
function pesquisarCNPJ($array,$CNPJ){
$i=1;
foreach($array as $valores){
    if($valores['CNPJ']==$CNPJ){
    return $i;
    }
$i++;
}
}
if(pesquisarCNPJ($array,"05651966000617")){
echo "CNPJ encontrado na posição".pesquisarCNPJ($array,"05651966000617");
}
else {
echo "Não encontrado";
}


?>

Or even using the php function itself:

echo $key = array_search($CNPJ, array_column($array, 'CNPJ'));

And in case, if there is more ed a cnpj, just save the indexes found in a new array, then you will have all the positions that the CNPJ exists

I hope I have helped

    
05.01.2017 / 14:14
2

See if it works for you:

function search($haystack, $needle, $index = NULL) {

if (is_null($haystack)) {
  return -1;
}

$arrayIterator = new \RecursiveArrayIterator($haystack);

$iterator = new \RecursiveIteratorIterator($arrayIterator);

while ($iterator->valid()) {

if (( ( isset($index) and ( $iterator->key() == $index ) ) or ( !isset($index) ) ) and ( $iterator->current() == $needle )) {

     return array('interator'=>$arrayIterator->key(),'position'=>$index);
   }

   $iterator->next();
 }
     return -1;
}
    
05.01.2017 / 14:19