9

我有 3 个数组,每个数组只有 7 个元素。数组是:

filename[]

title[]

description[]

我想为上面数组中的每个数据表达和迭代一个关联数组。filename可以是 assoc 数组的键值,但每个文件名都有自己对应的标题和描述。

以下是以下示例:

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" }
4

4 回答 4

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;
}

只需确保将有效输入传递给函数,或添加一些额外的检查。那是你要找的吗?

于 2012-11-13T03:18:57.903 回答
5

如果您的数组键对于所有 3 个数组都相同,那么执行您所要求的更好的方法是 foreach 创建一个新数组,其中所有键(文件名、标题、描述)都在同一个键中:

<?php
foreach($filename as $key => $file)
{
    $files[$key]['filename'] = $file;
    $files[$key]['title'] = $title[$key];
    $files[$key]['description'] = $description[$key];
}
?>
于 2012-11-13T03:24:48.300 回答
0

试试这个

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

或者,如果您需要内部数组是关联的。

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

如果你只想组合三个数组

$result = array_map(function($f, $t, $d) { 
    return array('filename'=>$f, 'title'=>$t, 'description'=>$d); 
  }, $filename, $title, $description
);
于 2012-11-13T03:20:26.873 回答
-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 />"; 
} 
于 2014-04-12T09:22:32.773 回答