Store array in while loop to use outside

后端 未结 4 457
星月不相逢
星月不相逢 2021-01-21 15:28

I would like to store value from while loop but not in multidimensional way :

 $movies_id = array();

 while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
          


        
相关标签:
4条回答
  • 2021-01-21 16:14

    You need to set value properly.

                $movies_id = array();
    
                while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
                    $id = $row['id'];
                    $title_id = $row['title_id'];
                        $movies_id[$id] = $title_id; // The proper way
                        //$movies_id[] = [$id => $title_id];
                }
    
                print_r($movies_id);
    

    The more readable code would be:

                $movies_id = array();
    
                while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
                        $movies_id[$row['id']] = $row['title_id'];
                }
                print_r($movies_id);
    

    And would result in

    array (
        1 => 'Title 1',
        2 => 'Title 2',
        4 => 'Title 4',
        8 => 'Title 8',
    )
    

    And key-less soulution would be:

                $movies_id = array();
    
                while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
                        $movies_id[] = $row['title_id'];
                }
                print_r($movies_id);
    

    And would result in

    array (
        0 => 'Title 1',
        1 => 'Title 2',
        2 => 'Title 4',
        3 => 'Title 8',
    )
    
    0 讨论(0)
  • 2021-01-21 16:14

    Instead of this line

    $movies_id[] = [$id => $title_id];
    

    Use the following

    $movies_id[$id] = $title_id;
    
    0 讨论(0)
  • 2021-01-21 16:19

    Your code would not work in case of PHP version less than 5.4. In that case you can use the following.

            $movies_id = array();
    
            while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
                $id = $row['id'];
                $title_id = $row['title_id'];
                $movies_id[] = array($id => $title_id);
            }
    
            print_r($movies_id);
    
    0 讨论(0)
  • 2021-01-21 16:33

    I may have misunderstood what you're aiming for, but this might do it:

    replace

    $movies_id[] = [$id => $title_id];
    

    with

     $movies_id[$id] = $title_id;
    
    0 讨论(0)
提交回复
热议问题