PHP将新数据添加到多维数组

时间:2014-05-12 16:09:25

标签: php wordpress multidimensional-array

我是多维阵列的新手

我有一个将数据存储到数组中的表单 我希望我的用户重新使用表单并将数据存储到数组中。
所以我的想法是一个多维数组,每次使用表单时都会存储一个新数组。

但我的问题是我不知道该怎么做。

这是我的表格:

            $customer = '';
            $customer .= '<tr><td>customername:<br/><input type="text" name="customer[customername]" value="" /> </td></tr>';
            $customer .= '<tr><td>customertitle 1:<br/><input type="text" name="customer[customertitle1]" value="" /> </td></tr>';
            $customer .= '<tr><td>customeremail 1:<br/><input type="text" name="customer[customeremail1]" value="" /> </td></tr>';
            $customer .= '<tr><td>customertitle 2:<br/><input type="text" name="customer[customertitle2]" value="" /> </td></tr>';
            $customer .= '<tr><td>customeremail 2:<br/><input type="text" name="customer[customeremail2]" value="" /> </td></tr>';
            echo $customer;

这将表单保存在数组中:

if(isset($_POST['Submit'])) {
$customer = $_POST['customer'];

这显示了数组的第一个值:

        $customers = array(get_option('customer'));
        foreach($customers as $customer){
          echo $customer["customername"];
        }           

我希望这能给任何人带来!!!!

2 个答案:

答案 0 :(得分:0)

是的想出来了

以下是希望了解的人: 首先创建一个函数来获取当前数组。 使用update_option

保存表单中的新值
function savearray (){
if(isset($_POST['Submit'])) {
// get the option
$customers = get_option( 'customers' );
// add new data to the option
$customers[] = $_POST['customers'];
// save it back to the db
update_option( 'customers', $customers );
}

然后创建一个将数据按名称放置在数组中的表单

<?php 
$customers = '';
$customers .= '<tr><td>Name:<br/><input type="text" name="customers[name]" value="" /> </td></tr>';
$customers .= '<tr><td>Contact 1:<br/><input type="text" name="customers[contact1]" value="" /> </td></tr>';
echo $customers;
?>

所以这很有效...... 现在是下一步。

我想只显示客户的名称,并创建指向特定客户数据的链接。 所以我这样做了:

 <?php      
$customers = get_option('customers');
foreach($customers as $val){
  echo '<a href="#">'.$val["name"] . '</a><br>';
}           
?>  

这告诉我,我想要查看tha数组中所有客户的名称并创建一个链接。 我不知道如何定位数组中的特定数据。

任何?????

答案 1 :(得分:-1)

我认为您需要使用ArrayObject

例如:

<?php
 // add a new consumer in your new array  
   $consumer["name"] = "John Doe";
   $consumer["email"] = "toto@yopmail.com";
   ...
   $a = new ArrayObject();
   $a->append($consumer)


   // for get a consumer in the array
    foreach ($arr as $key => $value)
    {
          // Some instruction
    }
?>

希望它能帮到你