php 带有多维数组的php foreach
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6413589/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
php foreach with multidimensional array
提问by medk
I'm developing a php app that uses a database class to query mySQL.
我正在开发一个使用数据库类来查询 mySQL 的 php 应用程序。
the class is here: http://net.tutsplus.com/tutorials/php/real-world-oop-with-php-and-mysql/
课程在这里:http: //net.tutsplus.com/tutorials/php/real-world-oop-with-php-and-mysql/
I made some tweaks on the class to fit my needs, but there is a problem (maybe a stupid one)
我对课程进行了一些调整以满足我的需要,但有一个问题(可能是一个愚蠢的问题)
When using select() it returns a multidimensional array like that for a table that has 3 cols (id, firstname, lastname):
使用 select() 时,它返回一个多维数组,类似于具有 3 个列(id、firstname、lastname)的表:
Array ( [0] => Array ( [id] => 1 [firstname] => Firstname one [lastname] => Lastname one ) [1] => Array ( [id] => 2 [firstname] => Firstname two [lastname] => Lastname two ) [2] => Array ( [id] => 3 [firstname] => Firstname three [lastname] => Lastname three ) )
Now I want this array to be used as a mysql result (mysql_fetch_assoc).
现在我想将此数组用作 mysql 结果 (mysql_fetch_assoc)。
I know that it may be used with foreach() but this is with simple arrays. so I think that I have to redeclare a new foreach() withing each foreach(), but I think this could slow down or cause some higher server load.
我知道它可以与 foreach() 一起使用,但这是与简单数组一起使用的。所以我认为我必须为每个 foreach() 重新声明一个新的 foreach(),但我认为这可能会减慢速度或导致更高的服务器负载。
So how to apply foreach() with this multidimensional array the simplest way?
那么如何以最简单的方式在这个多维数组中应用 foreach() 呢?
Thanks
谢谢
回答by Brad
You can use foreach here just fine.
你可以在这里使用 foreach 就好了。
foreach ($rows as $row) {
echo $row['id'];
echo $row['firstname'];
echo $row['lastname'];
}
I think you are used to accessing the data with numerical indicies (such as $row[0]
), but this is not necessary. We can use associative arraysto get the data we're after.
我认为您习惯于使用数字索引(例如$row[0]
)访问数据,但这不是必需的。我们可以使用关联数组来获取我们想要的数据。
回答by Karolis
You can use array_walk_recursive
:
您可以使用array_walk_recursive
:
array_walk_recursive($array, function ($item, $key) {
echo "$key holds $item\n";
});
回答by arvy3
This would have been a comment under Brad's answer, but I don't have a high enough reputation.
这本来是布拉德回答下的评论,但我的声誉不够高。
Recently I found that I needed the key of the multidimensional array too, i.e., it wasn't just an index for the array, in the foreach loop.
最近我发现我也需要多维数组的键,即它不仅仅是数组的索引,在 foreach 循环中。
In order to achieve that, you could use something very similar to the accepted answer, but instead split the key and value as follows
为了实现这一点,您可以使用与接受的答案非常相似的东西,而是按如下方式拆分键和值
foreach ($mda as $mdaKey => $mdaData) {
echo $mdaKey . ": " . $mdaData["value"];
}
Hope that helps someone.
希望能帮助某人。
回答by nao_de_naoned
With arrays in php, the foreach loop is always a pretty solution.
In this case it could be for example:
对于 php 中的数组,foreach 循环总是一个很好的解决方案。
在这种情况下,它可能是例如:
foreach($my_array as $number => $number_array)
{
foreach($number_array as $data = > $user_data)
{
print "Array number: $number, contains $data with $user_data. <br>";
}
}
回答by Asraful Haque
Holla/Hello, I got it! You can easily get the file name,tmp_name,file_size etc.So I will show you how to get file name with a line of code.
霍拉/你好,我知道了!您可以轻松获取文件名、tmp_name、file_size 等。所以我将向您展示如何使用一行代码获取文件名。
for ($i = 0 ; $i < count($files['name']); $i++) {
echo $files['name'][$i].'<br/>';
}
It is tested on my PC.
它在我的电脑上进行了测试。
回答by Rmj86
To get detail out of each value in a multidimensional array is quite straightforward once you have your array in place. So this is the array:
一旦你的数组就位,从多维数组中的每个值中获取细节是非常简单的。所以这是数组:
$example_array = array(
array('1','John','Smith'),
array('2','Dave','Jones'),
array('3','Bob','Williams')
);
Then use a foreach loop and have the array ran through like this:
然后使用 foreach 循环并让数组像这样运行:
foreach ($example_array as $value) {
echo $value[0]; //this will echo 1 on first cycle, 2 on second etc....
echo $value[1]; //this will echo John on first cycle, Dave on second etc....
echo $value[2]; //this will echo Smith on first cycle, Jones on second etc....
}
You can echo whatever you like around it to, so to echo into a table:
你可以在它周围回显任何你喜欢的东西,所以要回显到表格中:
echo "<table>"
foreach ($example_array as $value) {
echo "<tr><td>" . $value[0] . "</td>";
echo "<td>" . $value[1] . "</td>";
echo "<td>" . $value[2] . "</td></tr>";
}
echo "</table>";
Should give you a table like this:
应该给你一个这样的表:
|1|John|Smith |
|2|Dave|Jones |
|3|Bob |Williams|
回答by aorcsik
Example with mysql_fetch_assoc()
:
示例mysql_fetch_assoc()
:
while ($row = mysql_fetch_assoc($result))
{
/* ... your stuff ...*/
}
In your case with foreach
, with the $result
array you get from select()
:
在您的情况下foreach
,使用$result
您从中获得的数组select()
:
foreach ($result as $row)
{
/* ... your stuff ...*/
}
It's much like the same, with proper iteration.
它非常相似,具有适当的迭代。
回答by Poly
Ideally a multidimensional array is usually an array of arrays so i figured declare an empty array, then create key and value pairs from the db result in a separate array, finally push each array created on iteration into the outer array. you can return the outer array in case this is a separate function call. Hope that helps
理想情况下,多维数组通常是一个数组数组,所以我想声明一个空数组,然后从 db 结果创建键和值对在一个单独的数组中,最后将迭代时创建的每个数组推入外部数组。如果这是一个单独的函数调用,您可以返回外部数组。希望有帮助
$response = array();
foreach ($res as $result) {
$elements = array("firstname" => $result[0], "subject_name" => $result[1]);
array_push($response, $elements);
}
回答by Rotimi
I know this is quite an old answer.
Here is a faster solution without using foreach
:
我知道这是一个很老的答案。这是一个不使用的更快的解决方案foreach
:
Use array_column
用 array_column
print_r(array_column($array, 'firstname')); #returns the value associated with that key 'firstname'
Also you can check before executing the above operation
您也可以在执行上述操作之前进行检查
if(array_key_exists('firstname', $array)){
print_r(array_column($array, 'firstname'));
}
回答by Gregory Bologna
If you need to do string manipulation on array elements, e.g, then using callback function array_walk_recursive(or even array_walk) works well. Both come in handy when dynamically writing SQL statements.
如果您需要对数组元素进行字符串操作,例如,使用回调函数array_walk_recursive(甚至array_walk)效果很好。两者在动态编写 SQL 语句时都派上用场。
In this usage, I have this array with each element needing an appended comma and newline.
在这种用法中,我有这个数组,每个元素都需要附加逗号和换行符。
$some_array = [];
data in $some_array
0: "Some string in an array"
1: "Another string in an array"
$some_array 中的数据
0:“数组中的某个字符串”
1:“数组中的另一个字符串”
Per php.net
每个 php.net
If callbackneeds to be working with the actual values of the array, specify the first parameter of callback as a reference. Then, any changes made to those elements will be made in the original array itself.
如果回调需要处理数组的实际值,请指定回调的第一个参数作为引用。然后,对这些元素所做的任何更改都将在原始数组本身中进行。
array_walk_recursive($some_array, function (&$value, $key) {
$value .= ",\n";
});
Result:
"Some string in an array,\n"
"Another string in an array,\n"
结果:
“数组中的某个字符串,\n”
“数组中的另一个字符串,\n”
Here's the same concept using array_walk to prepend the database table name to the field.
这是使用 array_walk 将数据库表名添加到字段的相同概念。
$fields = [];
data in $fields:
0: "FirstName"
1: "LastName"
$fields 中的数据:
0:“名字”
1:“姓氏”
$tbl = "Employees"
array_walk($fields, 'prefixOnArray', $tbl.".");
function prefixOnArray(&$value, $key, $prefix) {
$value = $prefix.$value;
}
Result:
"Employees.FirstName"
"Employees.LastName"
结果:
“Employees.FirstName”
“Employees.LastName”
I would be curious to know if performance is at issue over foreach, but for an array with a handful of elements, IMHO, it's hardly worth considering.
我很想知道 foreach 是否存在性能问题,但是对于包含少量元素的数组,恕我直言,这几乎不值得考虑。