duanchui1251 2016-04-19 06:38
浏览 44
已采纳

从循环创建php数组,没有键中的大括号

I need to push value to an array from a for loop based on a count number found in the database.

Here is the scenario.

$num_images = 5;    
$numb_images = array();
        for ($x = 1; $x <= $num_images; $x++) {

            #$numb_images[] = array('image' . $x => '_image' . $x);
            $numb_images['image' . $x] = "_image" . $x;
        }

When I do print_r($numb_images), it will print the following

Array ( [image1] => _image1 [image2] => _image2 [image3] => _image3 [image4] => _image4 [image5] => _image5 )

2 issues. it prints the key with braces [] which I do not want.

2nd thing is, it is printing them all in same row.

This is exactly how I need it to populate

$numb_images = array(
        'image1' => '_image1',
        'image2' => '_image2',
    );

So the image1 => _image1 key/pair needs to be looped from the given number.

Any help will be highly appreciated.

Thanks

  • 写回答

1条回答 默认 最新

  • douxu3732 2016-04-19 06:50
    关注

    Function print_r is useful if you want to print what is stored in a variable. And it's outputs variable which you are created in right way.

    If you do print_r in array

    $numb_images = array(
            'image1' => '_image1',
            'image2' => '_image2',
        );
    

    result will be analogical:

    Array ( [image1] => _image1 [image2] => _image2 )
    

    So there is no issue. Function print_r prints in brackets [] key of array element.

    EDIT:

    You need foreach loop to show this fields. Assume that we have array like that:

    $numb_images = array(
            'image1' => '_image1',
            'image2' => '_image2',
            'image4' => '_image4',
            'image6' => '_image6',
        );
    

    Now to print this without knowing size of array you can use foreach:

    foreach($numb_images as $key => $value)
    {
        echo $key . '  ' . $value. '<br/>';
    }
    

    Output:

    image1 _image1
    image2 _image2
    image4 _image4
    image6 _image6
    

    More information about foreach: http://php.net/manual/en/control-structures.foreach.php

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?