2012-11-13 18 views
9

Mam 3 tablice, po 7 elementów w każdej. Tablice są:Jak połączyć 3 tablice w jedną tablicę asocjacyjną w PHP

filename[]

title[]

description[]

że chce ekspresji i iterację jednym asocjacyjnej dla każdego z danych zawartych w powyższych tablicach. filename może być kluczową wartością tablicy assoc, ale każda nazwa pliku ma swój własny tytuł i opis.

Poniżej znajduje się próbka:

var_dump($filename) 
    string(10) "IMG_1676_3" [1]=> 
    string(10) "IMG_0539_3" [2]=> 
    string(8) "IMG_1942" [3]=> 
    string(8) "IMG_1782" [4]=> 
    string(8) "IMG_2114" [5]=> 
    string(8) "IMG_9759" [6]=> 
    string(8) "IMG_2210" } 

var_dump($title) 
    string(31) "Lighthouse at Ericeira Portugal" [1]=> 
    string(23) "Gaudi park in Barcelona" [2]=> 
    string(32) "Driving around outside of Lisbon" [3]=> 
    string(16) "Madeira Portugal" [4]=> 
    string(15) "Barcelona Spain" [5]=> 
    string(15) "Lisbon Portugal" [6]=> 
    string(14) "Sailing Lisbon" } 

Odpowiedz

6
function mergeArrays($filenames, $titles, $descriptions) { 
    $result = array(); 

    foreach ($filenames as $key=>$name) { 
     $result[] = array('filename' => $name, 'title' => $titles[$key], 'descriptions' => $descriptions[ $key ]); 
    } 

    return $result; 
} 

Wystarczy upewnić się zdać ważny wkład do funkcji, lub dodać dodatkowe kontrole. Czy tego właśnie szukasz?

+0

Jak mogę nazwać tytuł lub opis moich danych pola z '$ res ult [0] '? – GivenPie

+0

'$ result [0] ['title']' lub '$ result [0] ['description']' –

0

Spróbuj

$result = array_combine($filename, array_map(null, $title, $description)); 
var_dump($result); 

Albo jeśli trzeba wewnętrzną tablicę być asocjacyjne.

$result = array_combine($filename, 
    array_map(function($t, $d) { 
     return array('title'=>$t, 'description'=>$d); 
    }, $title, $description 
) 
); 

Jeśli chcesz po prostu połączyć trzy tablice

$result = array_map(function($f, $t, $d) { 
    return array('filename'=>$f, 'title'=>$t, 'description'=>$d); 
    }, $filename, $title, $description 
); 
4

Jeśli klucz tablicy są takie same dla wszystkich 3 tablic, lepszym sposobem, aby robić to, co prosisz, jest tworzenie foreach nowa tablica zawierająca wszystkie kluczowe (nazwa pliku, tytuł, opis) w tym samym kluczu:

<?php 
foreach($filename as $key => $file) 
{ 
    $files[$key]['filename'] = $file; 
    $files[$key]['title'] = $title[$key]; 
    $files[$key]['description'] = $description[$key]; 
} 
?> 
+0

Bardzo podoba mi się twoja logika, myślę, że to zasługuje na najwyższą odpowiedź. – GivenPie

-1
$array1 = array("orange", "apple", "grape"); 
$array2 = array("peach", 88, "plumb"); 
$array3 = array("lemon", 342); 
$newArray = array_merge($array1, $array2, $array3); 
foreach ($newArray as $key => $value) { 
    echo "$key - <strong>$value</strong> <br />"; 
} 
+0

To rozwiązanie nie spełnia wymagań podanych w pytaniu. – automatix

Powiązane problemy