Php 有助于简化增加和增加的功能”;图像[]";排成一列

Php 有助于简化增加和增加的功能”;图像[]";排成一列,php,simplification,Php,Simplification,我最近一直在处理表单,并决定制作一个php脚本来简化我看到自己重复的一些方面,我不会发布我创建的完整怪物,但如果可能的话,我会请您帮助我简化以下代码: function add($name,$input,&$array) { $p = explode('[',$name); if(isset($p[1])) { list($key) = explode(']',$p[1]); if(ctype_digit($key)) { $array['forms'][$p[

我最近一直在处理表单,并决定制作一个php脚本来简化我看到自己重复的一些方面,我不会发布我创建的完整怪物,但如果可能的话,我会请您帮助我简化以下代码:

function add($name,$input,&$array)
{
 $p = explode('[',$name);
 if(isset($p[1]))
 {
  list($key) = explode(']',$p[1]);
  if(ctype_digit($key))
  {
    $array['forms'][$p[0]][$key] = $input;
  }else{
    $array['forms'][$p[0]][] = $input;
  } 
 }else{
    $array['forms'][$name] = $input;
 }
}


$array = array();
add('image[]','',$array);
add('image[8]','',$array);
add('image[1]','',$array);
add('image[]','',$array);

echo '<PLAINTEXT>';
print_r($array);
这里的问题是,如果您添加一个“image”作为$name,那么它必须像发布一样添加到数组中,因此它将是array(image=>data),如果您输入image[],那么它将是array(image=>array(0=>data))

我发现我的代码太庞大了,我发现,它解析“image[]”,但它不适合我,因为我需要单独添加名称

这个功能能变得更优雅吗

澄清:

是否有更好的方法将“name[]”添加到数组中,就好像它是要添加到数组中的名称列表的一部分一样

所以我需要一个parse_str替换,它不会覆盖$array。 例如:

但结果似乎是:

Array
(
    [image] => Array
        (
            [0] => test2
        )

)
但需要看起来像:

Array
(
    [image] => Array
        (
            [0] => test
            [1] => test1
            [2] => test2
        )

)

这将真正简化上述功能

好的,考虑到您的澄清,再次尝试:

function add($name,&$array)
{
    $type = explode('[',$name);
    $key = str_replace(array($type['0'], ']=', '[', ']'), '', $name);
    $array[$type['0']][] = $key;
}

$array = array();
add('image[]=test',$array);
add('image[test1]',$array);
add('image[]=test2',$array);
add('video[test5]',$array);

echo '<PLAINTEXT>';
print_r($array);
好的,最后一次!据我所知,没有合适的函数,整理现有代码也不是那么容易,但我已经尽了最大努力

function add($name,&$array)
{
    $type = explode('[',$name);
    $key = (!empty($type[1])) ? explode(']', $type[1]) : false;
    $value = str_replace(array($key[0], $type[0], ']=', '[', ']'), '', $name);
    if ($key[0]) $array[$type['0']][$key[0]] = $value;
    else $array[$type['0']][] = $value;
}

$array = array();
add('image[]=test',$array);
add('image[text8]=test4',$array);
add('image[]=test2',$array);
add('video[test5]',$array);

echo '<PLAINTEXT>';
print_r($array);

好的,考虑到您的澄清,再次尝试:

function add($name,&$array)
{
    $type = explode('[',$name);
    $key = str_replace(array($type['0'], ']=', '[', ']'), '', $name);
    $array[$type['0']][] = $key;
}

$array = array();
add('image[]=test',$array);
add('image[test1]',$array);
add('image[]=test2',$array);
add('video[test5]',$array);

echo '<PLAINTEXT>';
print_r($array);
好的,最后一次!据我所知,没有合适的函数,整理现有代码也不是那么容易,但我已经尽了最大努力

function add($name,&$array)
{
    $type = explode('[',$name);
    $key = (!empty($type[1])) ? explode(']', $type[1]) : false;
    $value = str_replace(array($key[0], $type[0], ']=', '[', ']'), '', $name);
    if ($key[0]) $array[$type['0']][$key[0]] = $value;
    else $array[$type['0']][] = $value;
}

$array = array();
add('image[]=test',$array);
add('image[text8]=test4',$array);
add('image[]=test2',$array);
add('video[test5]',$array);

echo '<PLAINTEXT>';
print_r($array);

也许加入一个数组\u merge\u recursive可以帮助您简化代码。根据John的方法签名,它可能看起来像这样:

function add($value, &$target) {
    $temp = array();
    parse_str($value, $temp);
    $target = array_merge_recursive($target, $temp);
}

$array = array();
add('image[]=test',$array);
add('image[text8]=test4',$array);
add('image[]=test2',$array);
add('video[test5]',$array);
这(正如我所预期的)也会产生

Array
(
    [image] => Array
        (
            [0] => test
            [text8] => test4
            [1] => test2
        )

    [video] => Array
        (
            [test5] => 
        )

)
希望这能有所帮助:)

编辑:

如果您希望具有完全相同的行为(以最少的行数),则始终可以重新生成查询字符串,附加值并再次解析它。结果代码不是最优的或漂亮的,但它完成了任务;)。插图:

function add($value, &$target) {
    $query = urldecode(http_build_query($target, '', '&'));
    $query = "{$query}&{$value}";
    parse_str($query, $target);
}

$array = array();

add($array, 'image[]');
add($array, 'image[8]=test4');
add($array, 'image[1]=test2');
add($array, 'image[]');

print_r($array);
会导致

Array
(
    [image] => Array
        (
            [0] => 
            [8] => test4
            [1] => test2
            [9] => 
        )

)

也许加入一个数组\u merge\u recursive可以帮助您简化代码。根据John的方法签名,它可能看起来像这样:

function add($value, &$target) {
    $temp = array();
    parse_str($value, $temp);
    $target = array_merge_recursive($target, $temp);
}

$array = array();
add('image[]=test',$array);
add('image[text8]=test4',$array);
add('image[]=test2',$array);
add('video[test5]',$array);
这(正如我所预期的)也会产生

Array
(
    [image] => Array
        (
            [0] => test
            [text8] => test4
            [1] => test2
        )

    [video] => Array
        (
            [test5] => 
        )

)
希望这能有所帮助:)

编辑:

如果您希望具有完全相同的行为(以最少的行数),则始终可以重新生成查询字符串,附加值并再次解析它。结果代码不是最优的或漂亮的,但它完成了任务;)。插图:

function add($value, &$target) {
    $query = urldecode(http_build_query($target, '', '&'));
    $query = "{$query}&{$value}";
    parse_str($query, $target);
}

$array = array();

add($array, 'image[]');
add($array, 'image[8]=test4');
add($array, 'image[1]=test2');
add($array, 'image[]');

print_r($array);
会导致

Array
(
    [image] => Array
        (
            [0] => 
            [8] => test4
            [1] => test2
            [9] => 
        )

)

我不太清楚为什么还没有提到preg,但这似乎是你真正想要的

function add( $input, &$target )
{
    // sanity check.  If the brackets are missing, add them.
    if( strpos( $input, '[' ) === FALSE )
    {
        $input = str_replace( '=', '[]=',  $input );
    }
    // The regex means, "Get the starting variable name segment" 
    // (begins with a letter here, you could just make it \w+)
    // followed by the portion between the left and right brackets
    // and finally by the value after the period until the end of the input
    preg_match( '/^([a-zA-Z]\w*)\[(\w*)\]=?(.*)$/', $input, $matches );

    // the first value in the matches array is the original string.
    array_shift( $matches );

    // sanity check -- if the string doesn't match the above regex, ignore it.
    if( !isset( $matches[ 1 ] ) ) return;
    $m1 = $matches[ 1 ];
    $m2 = ( isset( $matches[ 2 ] ) )? $matches[ 2 ]: NULL;

    // numeric keys are translated to the equivalent of array_push.
    if( is_numeric( $m1 ) || $m1 == "" )
    {
        $target[ $matches[ 0 ] ][] = $m2;
    }
    // non-numerics are kept as is.
    else
    {
        $target[ $matches[ 0 ] ][ $m1 ] = $m2;
    }
}

我不太清楚为什么还没有提到preg,但这似乎是你真正想要的

function add( $input, &$target )
{
    // sanity check.  If the brackets are missing, add them.
    if( strpos( $input, '[' ) === FALSE )
    {
        $input = str_replace( '=', '[]=',  $input );
    }
    // The regex means, "Get the starting variable name segment" 
    // (begins with a letter here, you could just make it \w+)
    // followed by the portion between the left and right brackets
    // and finally by the value after the period until the end of the input
    preg_match( '/^([a-zA-Z]\w*)\[(\w*)\]=?(.*)$/', $input, $matches );

    // the first value in the matches array is the original string.
    array_shift( $matches );

    // sanity check -- if the string doesn't match the above regex, ignore it.
    if( !isset( $matches[ 1 ] ) ) return;
    $m1 = $matches[ 1 ];
    $m2 = ( isset( $matches[ 2 ] ) )? $matches[ 2 ]: NULL;

    // numeric keys are translated to the equivalent of array_push.
    if( is_numeric( $m1 ) || $m1 == "" )
    {
        $target[ $matches[ 0 ] ][] = $m2;
    }
    // non-numerics are kept as is.
    else
    {
        $target[ $matches[ 0 ] ][ $m1 ] = $m2;
    }
}


为什么不能直接使用
$array['forms']['images'][1]=''
访问元素?为什么要让它成为PHP数组?为什么不按原样将其传递给HTML呢?尽管在POST数组中会有相同的图片(0-8-1-9)。我希望这是你想从这个不寻常的名字中得到的是的,它需要是0-8-1-9,它使用与POST、GET和parse_str相同的机制。我想知道是否可以一部分一部分地使用相同的机制。@Hannes我想设置它,而不是访问它。你为什么不能只使用
$array['forms'['images'][1]=''
访问元素?为什么要让它成为PHP数组?为什么不按原样将其传递给HTML呢?尽管在POST数组中会有相同的图片(0-8-1-9)。我希望这是您希望从这个不寻常的命名中得到的。是的,它需要是0-8-1-9,它使用与POST、GET和parse_str相同的机制。我想知道是否可以一部分一部分地使用相同的机制。@Hannes我想设置它,而不是访问它。感谢第二次尝试:)但是您的示例应该返回数组('image'=>array(0=>'test','test1'=>'',1=>'test2'),'video'=>array('test5'=>'')难道没有内置函数可以做到这一点吗?哈哈,最后一次尝试很好,我对你的耐心感到惊讶。但是!我发现你的代码中有一个错误,如果我设置图像[0],特定的0将被忽略,并将自动递增到更高的值!但它比我的“短”;)另外,它似乎不适用于“file=name”,这是一个有效的键值对。感谢您的第二次尝试:)但是您的示例应该返回数组('image'=>array(0=>'test','test1'=>'',1=>'test2'),'video'=>array('test5'=>''),难道没有一些内置函数可以做到这一点吗?哈哈,上次尝试很好,我对您的耐心感到惊讶。但是我在您的代码中发现了一个错误,如果我设置图像[0],特定的0将被忽略,并将自动递增到更高的值!但它比我的“短”;)此外,它似乎不适用于“file=name”,这是一个有效的键值对。它的行为与post不完全相同,因为它会忘记键(如果它们是数字),但我可以在这里找到用法;)很高兴你喜欢它:),我还添加了一个基于http_build_查询的替代方案,它应该会导致您的帖子中描述的行为;amp;amp;amp;图像而不仅仅是图像,它通过http_build_query($target,“,”&')修复了性能影响可以忽略不计。实际上,它可能不是最优的,但是如果post/get中的多级输入得到实现,您的函数将继续工作:)@YuriKolovsky对此表示抱歉。我相信在我的系统中默认设置为“&”,所以我自己没有注意到我的差异。好电话:)。我编辑了一个“最终”版本的答案。它的行为与post不完全一样,因为它会忘记键(如果它们是数字),但我可以在这里找到用法;)很高兴你喜欢它:),我还添加了一个基于http_build_查询的替代方案,它应该会导致您的帖子中描述的行为;amp;amp;amp;图像而不仅仅是图像,它通过http_build_query($ta)修复