2013-05-28 75 views
0

我那裏有2個初始場的應用程序:轉換複雜的數組foreach循環

  1. 名稱
  2. 價格

的形式如下:

<form> 
<input type="hidden" name="type" value="television" /> 
<label>Name <input type="text" name="name[]" /></label> 
<label>Price <input type="text"" name="price[]" /></label> 
</form> 

目前用戶可以「向表單添加更多」字段,這很好。因此,舉例來說,如果有人點擊添加更多按鈕形式如下:

<form> 
<input type="hidden" name="type" value="television" /> 

<label>Name <input type="text" name="name[]" /></label> 
<label>Price <input type="text"" name="price[]" /></label> 

<label>Name <input type="text" name="name[]" /></label> 
<label>Price <input type="text"" name="price[]" /></label> 
</form> 

,然後他們可以添加多個名稱/價格。我遇到的問題是,我無法將第一個價格字段與名字字段相關聯,等等,當我將其插入到數據庫中時,這是第四個。我使用ajax發佈數據,這也工作得很好。

目前,當我的var_dump後陣列看起來像這樣:

array(3) { 
    ["type"]=> 
    string(10) "television" 
    ["name"]=> 
    array(2) { 
    [0]=> 
    string(8) "name one" 
    [1]=> 
    string(8) "name two" 
    } 
    ["price"]=> 
    array(2) { 
    [0]=> 
    string(9) "price one" 
    [1]=> 
    string(9) "price two" 
    } 
} 

我需要的是合併數組值看起來正是這樣的能力:

array(
    "name" => "name one", 
    "price" => "price one", 
    "type" => "television" 
) 

array(
    "name" => "name two", 
    "price" => "price two", 
    "type" => "television" 
) 

任何幫助將非常感謝!

+0

它是一種常見的陣列轉變。你嘗試了什麼? – MatRt

回答

2

如果您知道每個name將有price,那麼您可以使用$_POST array variables中的任意key來創建輸出。

注:這不會創建單獨的陣列,但將組三一起更容易「可讀性」:

$_POST = array(
    "type"=> "television", 
    "name"=> array("name one","name two"), 
    "price"=> array("price one","price two"), 
); 

$output = array(); 
foreach($_POST['name'] as $key=>$name){ 
    $output[$key]['name'] = $name; 
    $output[$key]['price'] = $_POST['price'][$key]; 
    $output[$key]['type'] = $_POST['type']; 
} 
echo '<pre>',print_r($output),'</pre>'; 
+0

'$ _POST [$ key]'這不會工作。你有沒有試過你的答案?我認爲它是'$ _POST ['price'] [$ key]'而不是 – MatRt

+0

是的,在你的例子中,'$ key'是一個數字鍵(0,1,2 ..)所以'$ _POST [$ key ]'不會給你你想要的 – MatRt

+0

我從數組名稱倒退了'key'。道歉。 –