Search code examples
phparraysmultidimensional-array

Convert a flat array into an array of associative rows with predefined keys


How can I turn this array:

array(
    0 => Title1,
    1 => Title2,
    3 => Address1,
    4 => Address2,
)

into this array:

array (
    0 => array(
        'title' => 'Title1'
        'address' =>'Address1'
    ),
    1 => array(
        'title' => 'Title2',
        'address' => 'Address2'
    )
);

when you were initially given

$_POST['title'] = array('Title1', 'Title2');
$_POST['address'] = array('Address1', 'Address2');

which when merged would give you the first array I have given

I was able to solve this via a high level Arr:Rotate function in Kohana framework, along with Arr::merge function but I can't quite understand the implementation.


Solution

  • What about something like this :

    $_POST['title'] = array('Title1', 'Title2');
    $_POST['address'] = array('Address1', 'Address2');
    
    $result = array();
    $length = count($_POST['title']);
    
    for ($i=0 ; $i<$length ; $i++) {
        $result[$i]['title'] = $_POST['title'][$i];
        $result[$i]['address'] = $_POST['address'][$i];
    }
    
    var_dump($result);
    

    Which gives you the following result :

    array
      0 => 
        array
          'title' => string 'Title1' (length=6)
          'address' => string 'Address1' (length=8)
      1 => 
        array
          'title' => string 'Title2' (length=6)
          'address' => string 'Address2' (length=8)
    

    i.e. loop over both the title and address arrays you were initially given, and push their content into a new array -- without merging them or anything.