duanjianhe1388 2015-03-26 22:52 采纳率: 100%
浏览 78

PHP解析数组的帖子

A page is posting an array to me like this:

<input type="text" name="fields[email_address][value]" value="1" />
<input type="text" name="fields[first_name][value]" value="jim" />
<input type="text" name="fields[zip_code][value]" value="45254" />...

An array.

I can loop through it like this easy enough

    foreach ( $_POST['fields'] as $key => $field ) {

        echo $key." ".$field['value'] ;
        }

Result of above:

first_name jim
email_address 1
address_postal_code 45254

But what I really need to do is reference just the zip (45254) out of the array, maybe like:

echo $_POST['fields']['zip_code']; //or
echo $_POST['fields']['zip_code']['value']; 

result: 45254

Is this possible?

  • 写回答

2条回答 默认 最新

  • dongyan7851 2015-03-26 22:59
    关注

    Update

    <input type="text" name="fields[zip_code][value]" value="45254" />
    

    to be

    <input type="text" name="fields[zip_code]" value="45254" />
    

    Edit: I wasn't aware you can't modify the html, that wasn't specified in the original question.

    The only thing you can really do is do:

    $_POST['fields']['zip_code'] = $_POST['fields']['zip_code']['value'];
    

    However at that point, you might as well just assign $_POST['fields']['zip_code']['value'] to a variable and use that.

    If you can't update the html of the form, all you can do is manipulate the data after it's been assigned to the $_POST superglobal like it's any other array

    Edit 2: Adding a complete snippet to try:

    If you do, what do you get?:

    <?php
    foreach ( $_POST['fields'] as $key => $field ) {
        echo $key." ".$field['value'] ."<br />";
    }
    echo $_POST['fields']['zip_code']['value'] . "<br />";
    $_POST['fields']['zip_code'] = $_POST['fields']['zip_code']['value'];
    echo $_POST['fields']['zip_code'];
    ?>
    

    I just tried that with a simple form of:

    <form method="post" action="test.php">
      <input type="text" name="fields[email_address][value]" value="1" />
      <input type="text" name="fields[first_name][value]" value="jim" />
      <input type="text" name="fields[zip_code][value]" value="45254" />
      <input type="submit" />
    </form>
    

    And it works as expected.

    评论

报告相同问题?

悬赏问题

  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据