dongqiao1964 2012-04-21 16:01
浏览 24
已采纳

将2个关键数组合并为1个关联数组

I have 2 arrays, 1 called $person and the other called $classes. I'd like to merge the 2 together into 1 array and assign a name to item in the new merged array. Therefore creating an associative array as opposed to using keys that array_merge seems to be made by default using the array_merge function. (For clarity 1 person has multiple classes.)

Currently I have this:

($person)

[1]=>
   array(2) {
     ["Name"]=>
       string(1) "Bobby Moore"
     ["Age"]=>
       string(18) "36"

($classes)

   [1]=>
     array(2) {
     [0]=>
       array(11) {
         ["Class ID"]=>
           string(1) "12"
         ["Class Title"]=>
           string(18) "Math 101"
     [1]=>
       array(11) {
         ["Class ID"]=>
           string(1) "13"
         ["Class Title"]=>
           string(18) "Math 102"
     [1]=>
       array(11) {
         ["Class ID"]=>
           string(1) "14"
         ["Class Title"]=>
           string(18) "Math 103"

Is it possible to get the following result?

   [person]=>
     array(1) {
     [0]=>
       array(11) {
         ["Name"]=>
           string(1) "Bobby Moore"
         ["Ages"]=>
           string(18) "35"
   [Classes]=>
     array(2) {
     [0]=>
       array(11) {
         ["Class ID"]=>
           string(1) "12"
         ["Class Title"]=>
           string(18) "Math 101"
     [1]=>
       array(11) {
         ["Class ID"]=>
           string(1) "13"
         ["Class Title"]=>
           string(18) "Math 102"
     [1]=>
       array(11) {
         ["Class ID"]=>
           string(1) "14"
         ["Class Title"]=>
           string(18) "Math 103"

Currently I'm using array_merge($person ,$classes); which unfortunately is an array sorted by keys.

I hope this makes sense! Thank you in advance!

  • 写回答

1条回答 默认 最新

  • doushuo8677 2012-04-21 16:02
    关注

    Isn't it just a matter of doing

    $new_array = array( "person" => $person_array, "classes" => $class_array );
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?