[英]Grab value of array, in array, with for each
I have the following array: 我有以下数组:
print_r($all_projects);
--------------------------------
Array (
[0] => Array (
[pro_id] => 7
[0] => 7
)
[1] => Array (
[pro_id] => 20
[0] => 20
)
)
How do I grab each pro_id
in a foreach loop? 如何在foreach循环中获取每个pro_id
?
I can find quite a bit information online on how to create an array, and how to grab the key and value from an array. 我可以在网上找到很多有关如何创建数组以及如何从数组中获取键和值的信息。 But I have difficulty grabbing the value of a key in an array, in an array. 但是我很难在数组中获取键的值。
I currently have this for each: 我目前每个都有:
foreach ($all_projects as $project => $project_id){
echo $project_id;
}
Which in turn returns the following: 依次返回以下内容:
Array
Array
This makes sense to me, but how do I go deeper in the array? 这对我来说很有意义,但是我如何深入研究呢?
foreach($all_projects as $project) {
echo $project['pro_id'];
}
try: 尝试:
foreach ($all_projects as $project => $project_id){
echo $project_id['pro_id'];
}
or even cleaner to read : 甚至更干净地阅读:
foreach ($all_projects as $project){
echo $project['pro_id'];
}
foreach($all_projects as $KEY => $VALUE) {
echo "KEY: $KEY - PRO_ID: {$VALUE['pro_id']}";
}
In your case, you'd want: 对于您的情况,您需要:
foreach ($all_projects as $project_id => $project) {
echo $project_id . " = " . $project['pro_id'];
}
Now with PHP5.5, you have an easy way to do it: 现在使用PHP5.5,您可以轻松实现:
foreach ($all_projects as list($id))
echo $id;
And the old way: 和旧的方式:
foreach ($all_projects as $project)
echo $project['pro_id'];
Hope it'll help you! 希望对您有帮助!
If we're looping through the $all_projects
with foreach
loop this way, 如果我们这样用foreach
循环遍历$all_projects
,
foreach ($all_projects as $key => $project) {
echo($key);
}
then $key
will actually be 0, 1, etc., not 7 or 20 -- as you might intended this to be -- and $project
will be the content of the project. 那么$key
实际上将是0、1等,而不是7或20(正如您可能希望的那样),而$project
将是$project
的内容。
In your case, I presume that the "project id" you desired are stored inside the "project" array itself, so as other suggested, you should write something like 在您的情况下,我假设您想要的“项目ID”存储在“项目”数组本身中,因此,如其他建议所示,您应该编写类似
foreach($all_projects as $project) { // omitting the $key part since you don't need it
echo($project['pro_id']);
}
this will print the actual "project id", which is the pro_id
that you want. 这将打印实际的“项目ID”,即您想要的pro_id
。
If you were to improve this code, you might want to restructure your $all_projects
this way 如果要改进此代码,则可能需要以这种方式重组$all_projects
$all_projects = array();
$all_project[7] = $some_project; // your first project with id 7
$all_project[20] = $some_other_project; // your second project with id 20
then you will be able to use your original code to loop through: 那么您将能够使用原始代码循环遍历:
foreach($all_projects as $project_id => $project) {
echo($project_id);
}
with $project_id
be 7, 20, etc., and $project
be the content of your project. $project_id
等,而$project
的内容。
Hope this answers your question! 希望这能回答您的问题!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.