0

I found a way to search my multidimensional array and output the result and it works, however it only finds the first match and stops. If I have more than one match in the array I want to be able to show them all.

My array looks like this (the first layer of keys goes from 0, 1, 2 etc):

Array
(
    [0] => Array
        (
            [mydevice] => blahblah
            [ipadd] => 10.10.10.209
            [portnum] => 16040
        )

function searcharray($value, $key, $array) {
   foreach ($array as $k => $val) {
       if ($val[$key] == $value) {
           return $k;
       }
   }
   return null;
}

$myoutput = searcharray($ptn2, mydevice, $newresult);

I can then echo the results using something like $newresult[$myoutput][mydevice].

However if I have more than one entry in the array with a matching data in the 'mydevice' key it doesn't return them (just the first one).

2 Answers 2

1

That is because return breaks the function. You could use something like this:

function searcharray($value, $key, $array) {
    $result = array();    
    foreach ($array as $k => $val) {
        if ($val[$key] == $value) {
            $result[] = $k;
        }
    }
    return $result;
}

Now you will always get an array as result - empty if nothing was found. You can work with this like this e.g.

$mydevicekeys = searcharray($ptn2, "mydevice", $newresult);
foreach ($mydevicekeys as $mydevicekey) {
    // work with $newresult[ $mydevicekey ]["mydevice"]
}
Sign up to request clarification or add additional context in comments.

1 Comment

This works perfectly. It returns one or more results (if it finds more than one).
0

So add the results to an array :)

function searcharray($value, $key, $array) {
   $res = array();
   foreach ($array as $k => $val) {
       if ($val[$key] == $value) {
            $res[] = $key;
       }
   }
   return $res;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.