简体   繁体   中英

PHP - Use an Array to loop through a second Array

Using explode('<br>',$String) I have an Array1 with sub-Strings.

I want to use an Array2 as needles to loop through Array1 and if a Sub-String is found return Array2 values.

Example:

$Array1 { [0]=> string(3) "red"
          [1]=> string(4) "Blue"
          [3]=> string(5) "Black" };


$Array2 [
        'red' => "Red",
        'Yellow' => "Yellow"];

What is the best method/function to approach this task.

In the example above the Array1 ( Haystack) has a substring "red" , I want to be able to define Key => values in Array2 to use as needles and when for example a certain Key is found return its value.

// Output above

"Red"

Thanks

You can do it with a simple foreach loop

function getColorOrSomething(&$array1, &$array2){
    foreach($array2 as $key=>$value)
         if(in_array($key, $array1))
            return $value;


     return null; //no match found

}

and then of course call the function with the 2 arrays

$selected = getColorOrSomething($array1, $array2);

You can use a nested loop like this:

$key = "";
$value = "";

foreach( $Array1 as $ar1 ) {
    foreach( $Array2 as $ak2=>ar2 ) {
        if( preg_match("/" . $ak2 . "/", $ar1) ) {
            $key = $ak2;
            break;
        }

        if( $key != "" ) {
            $value = $ar1; 
            break;
        }
    }
}

echo "Key: " . $key . " & Value: " . $value;

Like so..

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM