2017-11-03 93 views
-1

我有這個下面的數組:更換陣列鍵

$arr = [ 'demo_key1' => 'demoval1', 'demo_key2' => 'demoval2' ]; 

和,我需要得到這個變換陣:

$arr = [ 'demo-key1' => 'demoval1', 'demo-key2' => 'demoval2' ]; 

所以,我想更換_到 - 數字,我該怎麼辦?

我嘗試了一些關於堆棧溢出的例子,我無法做到。

我非常感謝你的幫助。

+1

的可能的複製[?如何重新命名PHP數組鍵](https://stackoverflow.com/questions/ 9605143/How-to-rename-array-keys-in-php)或者[PHP在多維數組中重命名數組鍵](https://stackoverflow.com/questions/2212948/php-rename-array-keys-in-multidimensional - 數組)或[...](https://stackoverflow.com/search?q=%5Bphp%5D+rename+array+key) – Sean

+0

@Sean沒有任何工作。 – Jeremy

+1

顯示你已經嘗試過。我們不在這裏爲你做這項工作,而是爲你提供指導。 – Sean

回答

0

這裏有一個例子可以幫助你:

$arr=["demo0"=>"100","demo1"=>["demo_key1"=>"demoval1","demo_key2"=>"demoval2"],"demo3"=> "false"]; 

function changeKeys($array){ 
    $newArray=[]; 
    foreach($array as $key=>$val){ 
    $newKey=str_replace('_','-',$key); 
    if(is_array($val)){ 
     $newArray[$newKey]=changeKeys($val); 
    }else{ 
     $newArray[$newKey]=$val; 
    } 
    } 
    return $newArray; 
} 
$arr=changeKeys($arr); 

print_r($arr); 

輸出:

Array 
(
    [demo0] => 100 
    [demo1] => Array 
     (
      [demo-key1] => demoval1 
      [demo-key2] => demoval2 
     ) 

    [demo3] => false 
) 
+0

這是工作,但我不能使用功能,我會編輯現有的數組。 – Jeremy

+0

什麼不準確? –

+0

'[demo0] => 100 [demo1的] =>數組 ( [demo_key1] => demoval1 [demo_key2] => demoval2 ) [demo3] => FALSE'我需要直接更新它在主陣列。 – Jeremy

0

您可以使用array_keysstr_replacearray_valuesarray_combine在一個表達式:

$arr = array_combine(str_replace('_', '-', array_keys($arr)), array_values($arr)); 

如果你需要就地更換NT,也許因爲你要對數組的引用,那麼你可以做這樣的:

function cleanArrayKeys(&$arr) { // use a reference 
    $arr = array_combine(str_replace('_', '-', array_keys($arr)), array_values($arr)); 
} 

$arr = [ 'demo_key1' => 'demoval1', 'demo_key2' => 'demoval2' ]; 
cleanArrayKeys($arr); 

print_r($arr); // same array reference now has the updated keys 
+0

謝謝您的答覆,'[demo0] => 100 [demo1的] =>陣列 ( [demo_key1] => demoval1 [demo_key2] => demoval2 ) [demo3] =>假'我需要直接在主數組中更新它。你在這方面有什麼建議? – Jeremy

+0

鍵不能更新,只能替換。當你替換鍵(即刪除+重新創建)時,你可能會重新分配整個數組。但是你已經接受了一個答案,所以我想你沒問題。 – trincot

+0

我不能像這樣更新它嗎?'foreach($ arr as&$ value){if($ value == 1){ $ value = 2; } }' – Jeremy