帮助简化添加和递增“image[]”的函数到一个数组中

发布于 2024-09-29 02:33:55 字数 1797 浏览 4 评论 0原文

我最近一直在使用表单进行大量工作,并决定制作一个 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);

它将 $array 变成:

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

        )

)

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

我发现我的代码太庞大了,我发现 parse_str,其中解析“image[]”,但它没有为我服务,因为我需要单独添加名称......

这个函数可以变得更优雅吗?

澄清:

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

所以我需要一个不会覆盖 $array 的 parse_str 替换。 示例:

$array = array();
parse_str('image[]=test',$array);
parse_str('image[]=test1',$array);
parse_str('image[]=test2',$array);

但结果看起来像:

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

)

但需要看起来像:

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

)

这确实会简化上述函数!

I've been working a lot with forms lately and decided to make a php script to simplify some aspects that I see myself repeating, I won't post the full monstrosity that I have created, but instead I will ask you to help me simplify the following code if possible:

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);

it makes $array into:

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

        )

)

the problem here is that if you add a "image" as the $name, then it must be added to the array as if it was Posted, so it will be array(image=>data), if you enter image[], then it will be array(image=>array(0=>data)).

I find my code to be way too bulky, I found parse_str, which parses the "image[]", but it did not serve me as I need the names to be added separately...

Can this function be made more elegant?

clarification:

Is there a better way to add "name[]" into a array as if it was part of a list of names to be added to the array.

so I need a parse_str replacement that does not overwrite the $array.
Example:

$array = array();
parse_str('image[]=test',$array);
parse_str('image[]=test1',$array);
parse_str('image[]=test2',$array);

but the result looks like:

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

)

but needs to look like:

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

)

This would really simplify the above function!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

别挽留 2024-10-06 02:33:55

也许添加 array_merge_recursive 可以帮助您稍微简化代码。从约翰的方法签名开始工作,它可能看起来像这样:

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] => 
        )

)

Perhaps throwing in an array_merge_recursive can help you simplify your code a bit. Working from John's method signature it might look something like this :

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);

Which (as expected, I believe) also yields

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

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

)

Hopefully this helps :)

edit :

If you'd like to have exactly the same behavior (in a minimal amount of lines), you could always rebuild the query string, append your value and parse it again. The resulting code isn't optimal or pretty, but it does the job ;). Illustrated :

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);

Would result in

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

)
时光与爱终年不遇 2024-10-06 02:33:55

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

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);

将返回:

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

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

)

好的,最后一搏!据我所知,没有合适的函数,而且整理现有代码也不是那么容易,但我尽力了!

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);

将返回:

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

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

)

Right, another attempt with your clarification in mind:

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);

Will return:

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

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

)

OK, one last go! There isn't a suitable function to my knowledge, and its not terribly easy to tidy your existing code more than it is, but I did my best!

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);

Will return:

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

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

)
情深已缘浅 2024-10-06 02:33:55

我不太确定为什么 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;
    }
}

I'm not terribly sure why preg hasn't been mentioned yet, but that seems like that would be what you really want

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;
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文