dongwei4444 2018-05-08 16:58
浏览 11

PHP数组结合了问题

I've been struggling for a while trying to put these 2 arrays together and I'm wondering if you please may give me a hand here.

Here is my array1

$array1 = array('Name', 'Code', 'Email');

Here is my array2

$array2 = array(
  'user1', '12345', 'user1@example.com',
  'user2', '12345', 'user2@example.com',
  'user3', '12345', 'user3@example.com',
  'user4', '12345', 'user4@example.com',
  'user5', '12345', 'user5@example.com',
  'user6', '12345', 'user6@example.com'
);

I'm trying to come up with a new array where the indexes are the elements of array1 ('Name', 'code', 'email')... so it can end up as the following:

$array3 = (
  'Name'=>'user1', 'Code'=>'12345', 'Email'=>'user1@example.com'
  'Name'=>'user2', 'Code'=>'12345', 'Email'=>'user2@example.com'
  'Name'=>'user3', 'Code'=>'12345', 'Email'=>'user3@example.com'
  'Name'=>'user4', 'Code'=>'12345', 'Email'=>'user4@example.com'
  'Name'=>'user5', 'Code'=>'12345', 'Email'=>'user5@example.com'
  'Name'=>'user6', 'Code'=>'12345', 'Email'=>'user6@example.com'
); 

The reason of all this is to send it via json to a jquery response to present it to a table.

Would you please help me?

Thanks in advance.

  • 写回答

4条回答 默认 最新

  • doubi5127 2018-05-08 17:02
    关注

    Assuming that you have and array of arrays:

    $array1 = array('Name', 'Code', 'Email');
    
    $array2 = array(
        ['user1', '12345', 'user1@example.com'],
        ['user2', '12345', 'user2@example.com'],
        ['user3', '12345', 'user3@example.com'],
        ['user4', '12345', 'user4@example.com'],
        ['user5', '12345', 'user5@example.com'],
        ['user6', '12345', 'user6@example.com']
    );
    
    $array3 = [];
    foreach($array2 as $a2) {
        $array3[] = array_combine ($array1 , $a2 );
    }
    
    var_dump($array3);
    

    That will work. Otherwise, you gonna need a different approach, like this:

    $array1 = array('Name', 'Code', 'Email');
    
    $array2 = array(
        'user1', '12345', 'user1@example.com',
        'user2', '12345', 'user2@example.com',
        'user3', '12345', 'user3@example.com',
        'user4', '12345', 'user4@example.com',
        'user5', '12345', 'user5@example.com',
        'user6', '12345', 'user6@example.com'
    );
    
    $array3 = [];
    $i = 0;
    foreach($array2 as $a2) {
        $i++;
        $tempArray[] = $a2;
        if($i % 3 == 0) { //if is the 3rd element, combine then reset tempArray
            $array3[] = array_combine ($array1 , $tempArray );
            $tempArray = [];
        } 
    }
    
    var_dump($array3);
    
    评论

报告相同问题?