how to add elements to an array in a loop using php

前端 未结 4 1416
失恋的感觉
失恋的感觉 2021-01-13 05:25

I am dynamically trying to populate a multidimensional array and having some trouble.

I have a list of US states. Associative array like this $states[nc], $states[sc

相关标签:
4条回答
  • 2021-01-13 06:09

    In PHP, you can fill an array without referring to the actual index.

    $newArray = array();
    foreach($var in $oldArray){
    $newArray[] = $var;
    }
    
    0 讨论(0)
  • 2021-01-13 06:11
    foreach($states as $state) {
        $data[$state] = $state;
    
        foreach($state->cities as $city) {
          $data[$state][] = $city;
        }
    }
    

    Using empty brackets adds an element to the array.

    0 讨论(0)
  • 2021-01-13 06:30

    To add an element, use empty brackets.

    foreach($states as $state) {
        foreach($cities as $city) {
           $data[$state][] = $city;
        }
    }
    

    This will create an array like this

    array(
      'nc' => array('city1', 'city2', ...),
      'sc' => array('city1', 'city2', ...)
    )
    

    See manual under "Creating/modifying with square bracket syntax"

    0 讨论(0)
  • 2021-01-13 06:31

    The same way you add to an array when the key is not a concern:

    $data[$state]['cities'][] = $city;
    
    0 讨论(0)
提交回复
热议问题