简体   繁体   English

我如何遍历此php数组

[英]How can I iterate over this php array

I have this variable that INSERTs to a db the attached filename from a html form input. 我有这个变量INSERTs到DB从HTML形式输入所连接的文件名。

$insertAttachments->execute( array(':attachment2' => $attachment2) );

Now the problem is it INSERTs only one filename although the input is set to allow multiple. 现在的问题是它INSERTs虽然输入设置为允许多个只有一个文件名。 So I tried to do this: 所以我尝试这样做:

$uploads = count($attachment2);  //counts the number of attachments
for($i=0; $i<$uploads; $i++){
    $insertAttachments->execute( array(':attachment2' => $attachment2) );
}

which left me wondering where to place [$i] so that it iterates over array(':attachment2' => $attachment2) ? 这让我想知道将[$i]放在哪里,以便在array(':attachment2' => $attachment2)迭代?

If I assign it a variable and have it like - 如果我给它分配一个变量,并像-

$alluploads = array(':attachment2' => $attachment2);
for($i=0; $i<$uploads; $i++){
    $insertAttachments->execute( $alluploads[$i] );
}

It runs into an error. 它遇到一个错误。 Any ideas how I should pull this off? 有什么想法我应该如何实现吗? I'm extending a php 5.3 / slim framework application. 我正在扩展php 5.3 / slim框架应用程序。

Foreach let's you iterate over an associative array. Foreach让我们遍历一个关联数组。

$alluploads = array(':attachment2' => "attachment2");
foreach($alluploads as $key => $value){
    echo "key: " . $key . " Has value: ". $value ."\n";
}

https://3v4l.org/uPBug https://3v4l.org/uPBug


Here is an example with a for loop using array_keys to get the associative array keys and using that in the loop. 这是一个使用array_keys获取关联数组键并在循环中使用它的for循环示例。

$alluploads = array(':attachment2' => "attachment2");
$keys = array_keys($alluploads);
for($i=0;$i<count($keys);$i++){
    echo "key: " . $keys[$i] . " Has value: ". $alluploads[$keys[$i]] ."\n";
}

https://3v4l.org/45fnM https://3v4l.org/45fnM


And as a third example you can use array_values to remove the associative keys. 作为第三个示例,您可以使用array_values删除关联键。
This method should only be used if you know all the values in the arrays are uploads and should be treated the same. 仅当您知道数组中的所有值都是上载并且应被视为相同时,才应使用此方法。

$alluploads = array(':attachment2' => "attachment2");
$alluploads = array_values($alluploads);
for($i=0;$i<count($alluploads);$i++){
    echo "key: " . $i . " Has value: ". $alluploads[$i] ."\n";
}

https://3v4l.org/IrDrv https://3v4l.org/IrDrv

You can use a foreach loop, and that way you don't need the count, like this: 您可以使用foreach循环,这样就不需要计数了,如下所示:

foreach ($attachment2 as $a){
    $insertAttachments->execute( array(':attachment2' => $a['some index with the file path']) );
}

Don't forget to change the index o the array 不要忘记更改数组的索引

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM