2014-09-04 24 views
0

因此,我試圖使用$_POST將動態創建的一組字段保存到數據庫。基本上,我不知道如何讓選項保存爲每個字段集的對象,而不是作爲選項本身的數組。我很難形容......讓我解釋一下。將可重複字段選項保存到PHP對象數組

首先,屏幕上的東西看起來像here

這些字段通過jQuery動態創建,效果很好。下面是我已建立了表單字段:

<label>Calendar Name 
    <input name="name[]" id="name[]" type="text" value="<?php echo $calendars['name'][$key]; ?>"> 
</label> 
<label>Public URL 
    <input name="url[]" id="url[]" type="text" value="<?php echo $calendars['url'][$key]; ?>"> 
</label> 
<label>Color 
    <input name="color[]" id="color[]" type="text" value="<?php echo $calendars['color'][$key]; ?>"> 
</label> 

這是similar to this question,但我想我不知道我應該如何正在增加和排序正確使用JS的索引值,或者如果有一個PHP的解決方案我完全錯過了。

TL; DR基本上我怎麼可以用動態創建的表單重複字段集來生成類似foo [0] ['name']而不是foo ['name'] [0]的東西?

+0

你想基於行的分組要發送的數據不是根據輸入名稱正確嗎? – Rasclatt 2014-09-04 22:53:35

+0

@Rasclatt正是我想要做的,是的! – brianjohnhanna 2014-09-05 14:00:44

回答

0

我會後期處理它像這樣:

if(isset($_POST['name'])) { 
      // $i is how you are going to assign your keys 
      $i = 0; 
      // Loop through post array 
      foreach($_POST['name'] as $key => $value) { 
        // Assign your new array the key values of each post array 
        $_rows[$i]['name'] = $_POST['name'][$key]; 
        $_rows[$i]['url'] = $_POST['url'][$key]; 
        $_rows[$i]['color'] = $_POST['color'][$key]; 
        $i++; 
       } 
     /* Do some quick prints to see before and after 
      echo '<pre>'; 
      print_r($_POST); 
      print_r($_rows); 
      echo '</pre>'; 
     */ 
     } 
0

好了,所以我在做一個插件我的工作類似的東西,這是我想出了一個解決方案。我修改了我的代碼以嘗試匹配你正在嘗試完成的任務。

現在基於上面的代碼,我假設你有一個名爲calendars的後期元。因此,從那裏,我們需要修改你的代碼位:

// Get our saved post meta if it exists 
$calendars = get_post_meta($post_id, '_calendars', true); 

// Loop through all of our calendars and display the inputs  
if ($calendars) { 
    foreach ($calendars as $calendar) { 
    ?> 
     <label>Calendar Name 
      <input name="name[]" id="name[]" type="text" value="<?php echo $calendar['name']; ?>"> 
     </label> 
     <label>Public URL 
      <input name="url[]" id="url[]" type="text" value="<?php echo $calendar['url']; ?>"> 
     </label> 
     <label>Color 
      <input name="color[]" id="color[]" type="text" value="<?php echo $calendar['color']; ?>"> 
     </label>  
    <?php 
    } 
} 

在你保存功能,包括類似下面的代碼:

$old_calendar = get_post_meta($post_id, '_calendars', true); 
$new_calendar = array(); 

$name = $_POST['name']; 
$url = $_POST['url']; 
$color = $_POST['color']; 

// Just to get the number of calendars we have 
$count = count($name); 

for ($i = 0; $i < $count; $i++) { 

    $new_calendar[$i]['name'] = $name[$i]; // Need sanitation if desired 
    $new_calendar[$i]['url'] = $url[$i]; // Need sanitation if desired 
    $new_calendar[$i]['color'] = $color[$i]; // Need sanitation if desired 

} 

if (!empty($new_calendar) && $new_calendar != $old_calendar) 
    update_post_meta($post_id, '_calendars', $new_calendar); 
elseif (empty($new_calendar) && $old_calendar) 
    delete_post_meta($post_id, '_calendars', $old_calendar); 
相關問題