猿问

使用foreach从键中获取值(多维数组)

我有一个多维数组


(Array ( [filenames] => Array ( [0] => 2.jpeg [1] => 3.jpeg ) [sizes] => Array ( [0] => 0.00 MB [1] => 0.00 MB ) [temp_names] => Array ( [0] => /private/var/folders/np/sln14hvn3tsbzc4kpjjtp17c0000gn/T/phpLVhmBY [1] => /private/var/folders/np/sln14hvn3tsbzc4kpjjtp17c0000gn/T/phpoifsg0 ) [uploads] => Array ( [0] => /Users/sandro/Documents/bildgalerie/uploads/2.jpeg [1] => /Users/sandro/Documents/bildgalerie/uploads/3.jpeg ) ))

我想使用foreach从特定键(例如“文件名”)中获取所有值。


这是数组的一部分:


$uploadData = array(

    'filenames' => array(),

    'sizes' => array(),

    'temp_names' => array(),

    'uploads' => array()

);

这段代码还行不通,但是我不知道为什么:(


foreach ($uploadData as $row) {

    if (move_uploaded_file($row['temp_names'], $location . '/' . basename($row['filenames']))) {

        echo 'File uploaded.';

        echo '<br>';

    }

}

错误: Notice: Undefined index: filenames in X on line X


芜湖不芜
浏览 197回答 1
1回答

心有法竹

您无法理解foreach正在做什么以及如何构造数组。迭代给定数组的每个元素。您说过您的数据如下所示:$uploadData = [&nbsp; &nbsp; 'filenames' => ["2.jpeg", "3.jpeg"],&nbsp; &nbsp; 'sizes' => ["0.00 MB", "0.00 MB"],&nbsp; &nbsp; 'temp_names' => ["/private/var/folders/np/sln14hvn3tsbzc4kpjjtp17c0000gn/T/phpLVhmBY", "/private/var/folders/np/sln14hvn3tsbzc4kpjjtp17c0000gn/T/phpoifsg0"],&nbsp; &nbsp; 'uploads' => ["/Users/sandro/Documents/bildgalerie/uploads/2.jpeg", "/Users/sandro/Documents/bildgalerie/uploads/3.jpeg"],];因此,这是一个包含4个元素的数组。循环的每次迭代都会为您提供一个新元素。第一次迭代得到一个数组,["2.jpeg", "3.jpeg"]然后尝试访问该filenames数组的元素。显然没有一个。相反,您可以循环遍历以下子数组之一:foreach ($uploadData["filenames"] as $key => $value) {&nbsp; &nbsp; if (move_uploaded_file($uploadData["temp_names"][$key], $location . '/' . basename($value))) {&nbsp; &nbsp; &nbsp; &nbsp; echo 'File uploaded.';&nbsp; &nbsp; &nbsp; &nbsp; echo '<br>';&nbsp; &nbsp; }}在第一次迭代中,$key将会是0和$value将会是2.jpeg。您可以使用该键来获取其他子数组中的匹配值。
随时随地看视频慕课网APP
我要回答