简体   繁体   English

如何使用数组值的一部分作为新数组的键?

[英]How can I use part of an array value as key for a new array?

How can I loop through an array and use part of the value as key for a new array? 如何遍历数组并将值的一部分用作新数组的键?

Something like this: 像这样:

$I = glob("path/to/file/*.txt");
foreach($I as $i){
    //key = function_acting_on($i) | value = $i
}

For example, when I do this: 例如,当我这样做时:

$I = glob("path/to/file/*.txt");
foreach($I as $i){
    $new_array[] = $i;
}

This would automatically use numerical enumerated keys. 这将自动使用数字枚举键。 But in my code I want to use part of the value $i as key. 但是在我的代码中,我想使用$i值的一部分作为键。

array(4) {
  [0]=>
  string(3) "foo"
  [1]=>
  string(3) "bar"
  [2]=>
  string(5) "hello"
  [3]=>
  string(5) "world"
}

I used the accepted answer in the following way: 我通过以下方式使用了接受的答案:

$images = glob("images/*.txt");
foreach( $images as $image ){
    preg_match('$pattern',$image,$match);
    $value = (int)preg_replace($pattern_,'',$match[0]);
    $array[$value] = $image;
    }
ksort($array);
var_dump($array);

Noticing now that duplicate keys are suppressed. 现在注意到重复的键已被抑制。

As you wrote in the comments, if you want to use a particular value as key of your array for a new array, you can simply do it like this: 如您在注释中所写,如果要使用特定值作为新数组的数组键,则可以像这样简单地进行操作:

$I = glob("path/to/file/*.txt");
$newArray = [];
foreach($I as $i){
    if(isset($newArray[function_acting_on($i)])){
        if(!is_array($newArray[function_acting_on($i)]))
            $newArray[function_acting_on($i)] = [$newArray[function_acting_on($i)]];
        $newArray[function_acting_on($i)][] = $i;
    } else {
    $newArray[function_acting_on($i)] = $i; 
            //^^^^^^^^^^^^^^^^^^^^^ Just use the return value as key
    }
}

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

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