简体   繁体   English

PHP:不在 foreach 内循环

[英]PHP: not looping inside a foreach

I have this array:我有这个数组:

$flavours = array (
    0 => array(799390 => 'Banana',),
    1 => array(799391 => 'Chocolate',)
);

And now I inside a foreach looping a set from my database.现在我在一个 foreach 中循环我的数据库中的一个集合。 I get 'Banana' from the database and I need the array to give me 799390 .我从数据库中得到 'Banana' ,我需要数组给我799390

I have tried:我努力了:

‌‌array_search('Banana', $flavours); 

but it does not work unless I add:但除非我添加,否则它不起作用:

‌‌array_search('Banana', $flavours[0]); 

But I cannot add [0] as I won't be able to tell in which position 'Banana' flavour is in the array.但我无法添加[0] ,因为我无法分辨数组中的 position 'Banana' 风味。

Any solution apart from looping again inside a foreach??除了在 foreach 中再次循环之外,还有什么解决方案?

Thanks a ton万分感谢

First, we can use array_walk_recursive() to flatten your array, which just gets rid of your nested arrays.首先,我们可以使用array_walk_recursive()来展平您的数组,这只是摆脱了嵌套的 arrays。

Next, we use array_flip() to swap the keys/values in the flattened array.接下来,我们使用array_flip()来交换展平数组中的键/值。 This makes it easier to grab the ID for a specific term.这使得获取特定术语的 ID 变得更加容易。

<?php

$flavours = [
    [799390 => 'Banana'],
    [799391 => 'Chocolate']
];

//flatten array
//Produces: Array ( [799390] => Banana [799391] => Chocolate )
array_walk_recursive($flavours,
    function($v, $k) use (&$temp) { 
        $temp[$k] = $v; 
    }
);

//flip array. Swaps keys with values.
//Produces: Array ( [Banana] => 799390 [Chocolate] => 799391 )
$flavours = array_flip($temp);

Now you can get the ID pretty easily, such as $flavours['Banana'] .现在您可以很容易地获得 ID,例如$flavours['Banana']


If you have a very very large array, this method may become slow.如果您有一个非常非常大的数组,此方法可能会变慢。 However, I tested this with 100,000 values on my cheap webhost, and ran this method a few times (20-25 times).但是,我在廉价的虚拟主机上用 100,000 个值对此进行了测试,并运行了该方法几次(20-25 次)。 It is finishing consistently at around (usually under) 0.1 milliseconds, which is about 0.0014 seconds.它始终以大约(通常低于)0.1 毫秒(大约 0.0014 秒)完成。

You can insert an if statement to set a condition for your loop as您可以插入一个if语句来为您的循环设置一个条件

foreach ($flavours as $key => $value) {
  if($key =  array_search('Banana', $value)){
   echo $key; 
 }
}

Output Output

799390

If the word being searched for is a different case many of the usual array methods will not work when trying to find the match, using preg_grep however will allow matches to be found in a case-insensitive manner.如果要搜索的单词是不同的大小写,许多常用的数组方法在尝试查找匹配项时将不起作用,但是使用preg_grep将允许以不区分大小写的方式找到匹配项。

function findflavour( $search, $haystack ){
    foreach( $haystack as $index => $arr ){
        $res=preg_grep( sprintf( '@%s@i', $search ), $arr );
        if( !empty( $res ) ) return array_search( array_values( $res )[0], $arr );
    }
    return false;
}



$search='BaNanA';
$flavours=array(
    array( 799390 => 'Banana' ),
    array( 799391 => 'Chocolate' ),
    array( 729361 => 'Chilli' ),
    array( 879695 => 'Apple' ),
    array( 995323 => 'Avacado' ),
    array( 528362 => 'Orange' ),
    array( 723371 => 'Cherry' ),
);


printf( 'Key:%s', findflavour( $search, $flavours ) );

If there might be multiple elements in the source array with the same value but different IDs a slightly different version of the findflavour function如果源数组中可能有多个元素具有相同的值但不同的 ID,则findflavour function 的版本略有不同

function findflavour( $search, $haystack, $multiple=false ){
    $keys=[];
    foreach( $haystack as $index => $arr ){
        $res=preg_grep( sprintf( '@%s@i', $search ), $arr );
        if( !empty( $res ) ) {
            $key=array_search( array_values( $res )[0], $arr );
            if( $multiple )$keys[]=$key;
            else return $key;
        }
    }
    return $multiple ? $keys : false;
}


$multiple=true;
$search='AVacAdo';
$flavours=array(
    array( 799390 => 'Banana' ),
    array( 799391 => 'Chocolate' ),
    array( 291333 => 'Avacado' ),
    array( 729361 => 'Chilli' ),
    array( 879695 => 'Apple' ),
    array( 995323 => 'Avacado' ),
    array( 528362 => 'Orange' ),
    array( 723371 => 'Cherry' ),
);


printf( 'Key(s): %s', print_r( findflavour( $search, $flavours, $multiple ), true ) );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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