Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
451 views
in Technique[技术] by (71.8m points)

array combine three or more arrays with php

ok, assuming I have 5 arrays, all just indexed arrays, and I would like to combine them, this is the best way I can figure, is there a better way to handle this?

function mymap_arrays(){
    $args=func_get_args();
    $key=array_shift($args);
    return array_combine($key,$args);
}
$keys=array('u1','u2','u3');
$names=array('Bob','Fred','Joe');
$emails=array('[email protected]','[email protected]','[email protected]');
$ids=array(1,2,3);
$u_keys=array_fill(0,count($names),array('name','email','id'));
$users=array_combine($keys,array_map('mymap_arrays',$u_keys,$names,$emails,$ids));

this returns:

Array
(
    [u1] => Array
        (
            [name] => Bob
            [email] => [email protected]
            [id] => 1
        )

    [u2] => Array
        (
            [name] => Fred
            [email] => [email protected]
            [id] => 2
        )

    [u3] => Array
        (
            [name] => Joe
            [email] => [email protected]
            [id] => 3
        )

)

EDIT: After lots of benchmarking I wend with a version of Glass Robots answer to handle a variable number of arrays, it's slower than his obviously, but faster than my original:

function test_my_new(){
    $args=func_get_args();
    $keys=array_shift($args);
    $vkeys=array_shift($args);
    $results=array();
    foreach($args as $key=>$array){
        $vkey=array_shift($vkeys);
        foreach($array as $akey=>$val){
            $result[$keys[$akey]][$vkey]=$val;
        }
    }
    return $result;
}
$keys=array('u1','u2','u3');
$names=array('Bob','Fred','Joe');
$emails=array('[email protected]','[email protected]','[email protected]');
$ids=array(1,2,3);
$vkeys=array('name','email','id');
test_my_new($keys,$vkeys,$names,$emails,$ids);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Personally for readability I would do it this way:

$keys   = array('u1','u2','u3');
$names  = array('Bob','Fred','Joe');
$emails = array('[email protected]','[email protected]','[email protected]');
$ids    = array(1,2,3);
$result = array();

foreach ($keys as $id => $key) {
    $result[$key] = array(
        'name'  => $names[$id],
        'email' => $emails[$id],
        'id'    => $ids[$id],
    );
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...