【问题标题】:Arrange and array in a order in php?在php中按顺序排列和排列?
【发布时间】:2017-07-12 07:23:00
【问题描述】:

我有一张上传多张图片的表格..表格中的字段是

++++++++++++++++++++++++++
id,user_id,photo,position
++++++++++++++++++++++++++

一个用户 ID最多可以有 8 张图片

现在如果用户在假设 1、3、5 位置上传图片

当我从数据库中获取后必须返回数组时

我将获得 1 、 3 、 5 位置的值,但我必须返回从 1 到 8 的所有位置的数组

因此,根据要求,位置 1 将具有数据库中的值 1,因为数据库中有值,但位置 2 没有值,因此在数组中位置 2 将为空白...

基本上数据库中有值的位置将保存数据库中的值,而数据库中没有值的位置将是空白的

位置是 1 2 3 4 5 6 7 8

在php中怎么做?

【问题讨论】:

标签: php arrays


【解决方案1】:

选择一个以位置为数组键的数组 比如……

$image[position] = image_name;

代码

$image[1] = image1;
$image[3] = $image3;
$image[5] = $image5;

现在运行一个for循环如下

for($i=0;$i<8;$i++){
    if(!isset($image[$i])) $image[$i] = '';
}

你得到了你想要的 $image 数组的结果;

【讨论】:

    【解决方案2】:

    您无法从那里不存在的表中获取值。所以写这样的代码

    $Something = 'test';
    $aFromTable = array (1=>$Something,3=>$Something,5=>$Something);
    
    for ($i=1;$i<9;$i++)
    {
        if (!isset($aFromTable[$i]))
            $aFromTable[$i] = $Something;
    }
    
    var_dump($aFromTable);
    

    或者像这样

    $Something = 'test';
    $aStandard[1] =  null;
    $aStandard[2] =  null;
    $aStandard[3] =  null;
    $aStandard[4] =  null;
    $aStandard[5] =  null;
    $aStandard[6] =  null;
    $aStandard[7] =  null;
    $aStandard[8] =  null;
    $aFromTable = array (1=>$Something,3=>$Something,5=>$Something);
    
    
    $aFromTable = $aFromTable + $aStandard;
    var_dump($aFromTable);
    

    【讨论】:

      【解决方案3】:
      <?php
      $rows = [
          ['foo.jpg', 8],
          ['bar.jpg', 4],
          ['baz.jpg', 1]
      ];
      
      $positions = array_fill(1, 8, null);
      
      foreach($rows as $row) {
          $positions[$row[1]] = $row[0];
      }
      
      var_export($positions);
      

      输出:

      array (
        1 => 'baz.jpg',
        2 => NULL,
        3 => NULL,
        4 => 'bar.jpg',
        5 => NULL,
        6 => NULL,
        7 => NULL,
        8 => 'foo.jpg',
      )
      

      用于生成行数组的示例 SQL:

      SELECT photo, position FROM photo_table WHERE user_id = 3
      

      【讨论】:

        猜你喜欢
        • 2015-12-09
        • 2020-03-29
        • 2019-01-08
        • 1970-01-01
        • 1970-01-01
        • 2017-12-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多