2

配列スタイルの名前で投稿されたフォーム入力があるとします:

<input type="text" name="user[name]" value="John" />
<input type="text" name="user[email]" value="foo@example.org" />
<input type="checkbox" name="user[prefs][]" value="1" checked="checked" />
<input type="checkbox" name="user[prefs][]" value="2" checked="checked" />
<input type="text" name="other[example][var]" value="foo" />

その後$_POST、次のように返されますprint_r()

Array
(
    [user] => Array
        (
            [name] => John
            [email] => foo@example.org
            [prefs] => Array
                (
                    [0] => 1
                    [1] => 2
                )

        )

    [other] => Array
        (
            [example] => Array
                (
                    [var] => foo
                )

        )

)

目標は、次のように関数を呼び出せるようにすることです。

$form_values = form_values($_POST);

これは、元の入力名のスタイルに似たキーを持つ連想配列を返します。

Array
(
    [user[name]] => John
    [user[email]] => foo@example.org
    [user[prefs][]] => Array
        (
            [0] => 1
            [1] => 2
        )

    [other[example][var]] => foo
)

これは非常に困難であり、この時点で私の「車輪は泥の中で回転しています」。:-[

4

2 に答える 2

1

あなたがそれをテストしたいのであれば、まあ、私はそれを行う私のクレイジーな方法を試しました.

<?php
function buildArray($input, &$output, $inputkey='')
{
    foreach($input as $key => $value)
    {
        if(is_array($value))
        {
            if($inputkey != "")
            {
                $inputkey .= "[$key]";
                buildArray($value, $output, $inputkey);
            }
            else
            {
                buildArray($value, $output, $key);
            }

        }
        else
        {
             $output[$inputkey."[$key]"] = $value;
        }
    }
 }

 $output = array();
 $input = array("user"=>array("name"=>"John","Email"=>"test.com","prefs"=>array(1,2)), "other"=>array("example"=>array("var"=>"foo")));
 buildArray($input, $output);
 print_r($output);
?>

私はまだそれらを学んでいないので、ほとんどの組み込みPHP関数の力を知りません。そのため、独自の再帰的な方法を思いつきました。

于 2012-10-19T15:11:19.417 に答える
1

なぜこれを行う必要があるのか​​ わかりませんが、次のコードがヒントになる場合:

$testArray = array ( 'user' => array ( 'name' => 'John', 'email' => 'test@example.org', 'prefs' => array ( 0 => '1', ), ), 'other' => array ( 'example' => array ( 'var' => 'foo', ), ), );

function toPlain($in,$track=null)
{
    $ret = array();
    foreach ($in as $k => $v) {
        $encappedKey = $track ? "[$k]" : $k; /* If it's a root */

        if (is_array($v)) {
            $ret = array_merge($ret,toPlain($v,$track.$encappedKey));
        } else {
            $ret = array_merge($ret,array($track.$encappedKey => $v));
        }
    }
    return $ret;
}
print_r(toPlain($testArray));

http://codepad.org/UAo9qNwo

于 2012-10-19T14:51:45.727 に答える