Add data dynamically to an Array

前端 未结 10 641
南方客
南方客 2020-12-13 09:15

I want to add data to an array dynamically. How can I do that? Example

$arr1 = [
    \'aaa\',
    \'bbb\',
    \'ccc\',
];
// How can I now add another value?         


        
相关标签:
10条回答
  • 2020-12-13 09:40

    Let's say you have defined an empty array:

    $myArr = array();
    

    If you want to simply add an element, e.g. 'New Element to Array', write

    $myArr[] = 'New Element to Array';
    

    if you are calling the data from the database, below code will work fine

    $sql = "SELECT $element FROM $table";
    $query = mysql_query($sql);
    if(mysql_num_rows($query) > 0)//if it finds any row
    {
       while($result = mysql_fetch_object($query))
       {
          //adding data to the array
          $myArr[] = $result->$element;
       }
    }
    
    0 讨论(0)
  • 2020-12-13 09:43

    Fastest way I think

           $newArray = array();
    
    for($count == 0;$row = mysql_fetch_assoc($getResults);$count++)
        {
        foreach($row as $key => $value)
        { 
        $newArray[$count]{$key} = $row[$key];
        }
    }
    
    0 讨论(0)
  • 2020-12-13 09:44

    In additon to directly accessing the array, there is also

    array_push — Push one or more elements onto the end of array

    0 讨论(0)
  • 2020-12-13 09:45
    $array[] = 'Hi';
    

    pushes on top of the array.

    $array['Hi'] = 'FooBar';
    

    sets a specific index.

    0 讨论(0)
  • 2020-12-13 09:47

    There are quite a few ways to work with dynamic arrays in PHP. Initialise an array:

    $array = array();
    

    Add to an array:

    $array[] = "item"; // for your $arr1 
    $array[$key] = "item"; // for your $arr2
    array_push($array, "item", "another item");
    

    Remove from an array:

    $item = array_pop($array);
    $item = array_shift($array);
    unset($array[$key]);
    

    There are plenty more ways, these are just some examples.

    0 讨论(0)
  • 2020-12-13 09:47

    You should use method array_push to add value or array to array exists

    $stack = array("orange", "banana");
    array_push($stack, "apple", "raspberry");
    print_r($stack);
    
    /** GENERATED OUTPUT
    Array
    (
        [0] => orange
        [1] => banana
        [2] => apple
        [3] => raspberry
    )
    */
    
    0 讨论(0)
提交回复
热议问题