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

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

报告相同问题?

悬赏问题

  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效