most efficient method of turning multiple 1D arrays into columns of a 2D array

Posted by Ty W on Stack Overflow See other posts from Stack Overflow or by Ty W
Published on 2010-04-05T20:48:07Z Indexed on 2010/04/05 20:53 UTC
Read the original article Hit count: 229

Filed under:
|
|

As I was writing a for loop earlier today, I thought that there must be a neater way of doing this... so I figured I'd ask. I looked briefly for a duplicate question but didn't see anything obvious.

The Problem:

Given N arrays of length M, turn them into a M-row by N-column 2D array

Example:

$id   = [1,5,2,8,6]
$name = [a,b,c,d,e]
$result = [[1,a],
           [5,b],
           [2,c],
           [8,d],
           [6,e]]

My Solution:

Pretty straight forward and probably not optimal, but it does work:

<?php
// $row is returned from a DB query
// $row['<var>'] is a comma separated string of values
$categories = array();
$ids = explode(",", $row['ids']);
$names = explode(",", $row['names']);
$titles = explode(",", $row['titles']);
for($i = 0; $i < count($ids); $i++) {
    $categories[] = array("id" => $ids[$i],
                          "name" => $names[$i],
                          "title" => $titles[$i]);
}
?>

note: I didn't put the name => value bit in the spec, but it'd be awesome if there was some way to keep that as well.

© Stack Overflow or respective owner

Related posts about php

Related posts about arrays