【问题标题】:create single array from different values从不同的值创建单个数组
【发布时间】:2015-07-02 13:50:16
【问题描述】:

我有一个非常基本的列表查询,我希望在单个数组中显示所有列表

$sql = "SELECT * FROM vendor";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) 
    {
        while($row = mysqli_fetch_assoc($result)) 
            {
                echo"<pre>";
                    print_r($row);
                echo "</pre>";
            }
    } 

我得到的结果是

Array
(
    [id] => 1
    [email] => 
    [password] => 
    [status] => 
)

Array
(
    [id] => 2
    [email] => 
    [password] => 
    [status] => 
)

Array
(
    [id] => 3
    [email] => 
    [password] => 
    [status] => 
)

但是我希望得到看起来像这样的结果。

Array
(
   [0] => Array
    (
        [id] => 1
        [email] => 
        [password] => 
        [status] => 
    )
   [1] => Array
    (
        [id] => 1
        [email] => 
        [password] => 
        [status] => 
    )
)

谁能告诉我如何获得这个结果

【问题讨论】:

    标签: mysql sql arrays multidimensional-array mysqli


    【解决方案1】:

    首先您需要将所有行存储到 attaylist 中,然后打印

    $sql = "SELECT * FROM vendor";
    $result = mysqli_query($conn, $sql);
    $resulyArray = array();
    if (mysqli_num_rows($result) > 0) 
        {
            while($row = mysqli_fetch_assoc($result)) 
                {
        array_push($resulyArray , $row);
    
    
                }
        } 
    
    
    echo"<pre>";
      print_r($resulyArray);
    echo "</pre>";
    

    【讨论】:

    • 谢谢你能告诉我一件事,我正在尝试通过 echo json_encode(array('list'=>$posts), JSON_UNESCAPED_UNICODE); 将结果转换为 json;但它给出的结果是空白的,你能帮我解决一下吗
    • 确保list'=&gt;$posts 有一个值。
    • 我刚刚将 resulyArray 重命名为帖子,是的 $posts 包含整个数组
    【解决方案2】:

    您只需将行插入到父数组中,即可获得所需的输出。通过声明一个空数组来执行此操作,然后开始循环遍历结果,然后将每一行推入该父数组。见下文。

    $sql = "SELECT * FROM vendor";
    $result = mysqli_query($conn, $sql);
    $res = array(); // parent array here
    if (mysqli_num_rows($result) > 0) 
        {
            while($row = mysqli_fetch_assoc($result)) 
                {
                    $array[] = $row; // push row into parent array
                }
        }
    echo "<pre>"; 
    print_r($res);
    echo "</pre>";
    

    【讨论】:

      猜你喜欢
      • 2017-11-19
      • 1970-01-01
      • 2020-08-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多