簡體   English   中英

如何使用數組值的一部分作為新數組的鍵?

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

如何遍歷數組並將值的一部分用作新數組的鍵?

像這樣:

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

例如,當我這樣做時:

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

這將自動使用數字枚舉鍵。 但是在我的代碼中,我想使用$i值的一部分作為鍵。

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

我通過以下方式使用了接受的答案:

$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);

現在注意到重復的鍵已被抑制。

如您在注釋中所寫,如果要使用特定值作為新數組的數組鍵,則可以像這樣簡單地進行操作:

$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