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 matlab数字图像处理频率域滤波
  • ¥15 在abaqus做了二维正交切削模型,给刀具添加了超声振动条件后输出切削力为什么比普通切削增大这么多
  • ¥15 ELGamal和paillier计算效率谁快?
  • ¥15 file converter 转换格式失败 报错 Error marking filters as finished,如何解决?
  • ¥15 ubuntu系统下挂载磁盘上执行./提示权限不够
  • ¥15 Arcgis相交分析无法绘制一个或多个图形
  • ¥15 关于#r语言#的问题:差异分析前数据准备,报错Error in data[, sampleName1] : subscript out of bounds请问怎么解决呀以下是全部代码:
  • ¥15 seatunnel-web使用SQL组件时候后台报错,无法找到表格
  • ¥15 fpga自动售货机数码管(相关搜索:数字时钟)
  • ¥15 用前端向数据库插入数据,通过debug发现数据能走到后端,但是放行之后就会提示错误