2017-08-30 99 views
-1

我有一個這樣的數組:PHP指數數組關聯第一元素等於第二等

$actions = array(
    "controller", 
    "index", 
    "method", 
    "default", 
); 

我想要得到的第一個關鍵等於第二鍵等等這樣

$actions = array(
    "controller" => "index", 
    "method" => "default" 
); 

我該如何做到這一點,謝謝!

+0

在[所以]你應該嘗試**自己寫代碼**。後** [做更多的研究](//meta.stackoverflow.com/questions/261592)**如果你有問題,你可以**發佈你已經嘗試**與清楚的解釋是什麼是'工作**並提供[** Minimal,Complete和Verifiable示例**](// stackoverflow.com/help/mcve)。我建議閱讀[問]一個好問題和[完美問題](http://codeblog.jonskeet.uk/2010/08/29/writing-the-perfect-question/)。另外,一定要參加[遊覽]並閱讀[this](// meta.stackoverflow.com/questions/347937/)**。 –

+1

循環遍歷你的數組使用for循環在這裏檢查循環http://php.net/manual/en/control-structures.for.php –

回答

2

這裏是一個for循環的例子: -

<?php 

$actions = array(
    "controller", 
    "index", 
    "method", 
    "default", 
); 

for($i = 0; $i < count($actions); $i++) 
{ 
    $arr[$actions[$i]] = $actions[$i += 1]; 
} 

echo "<pre>"; 
print_r($arr); 
-1

你可以這樣做

for($i=0;i<count($actions);$i+=2) 
{ 
$array[$actions[$i]]=$actions[$i+1]; 
} 
$actions=$array; 

做某事如果您確信包含偶數個元素。

相關問題