以数组的形式获取数组的值,每个数组的值

时间:2013-06-27 15:38:03

标签: php arrays key

我有以下数组:

print_r($all_projects);
--------------------------------
Array ( 
       [0] => Array ( 
                     [pro_id] => 7 
                     [0] => 7 
                    ) 
       [1] => Array ( 
                     [pro_id] => 20 
                     [0] => 20 
                     ) 
) 

如何在foreach循环中抓取每个pro_id? 我可以在网上找到有关如何创建数组的相关信息,以及如何从数组中获取键和值。但是我很难在数组中获取数组中键的值。

我目前每个都有这个:

foreach ($all_projects as $project => $project_id){ 
echo $project_id;
}

反过来又返回以下内容:

Array
Array

这对我有意义,但如何在数组中使用deeper

5 个答案:

答案 0 :(得分:3)

foreach($all_projects as $project) {
    echo $project['pro_id'];
}

答案 1 :(得分:0)

尝试:

foreach ($all_projects as $project => $project_id){ 
  echo $project_id['pro_id'];
}

甚至更清洁阅读:

foreach ($all_projects as $project){ 
  echo $project['pro_id'];
}

答案 2 :(得分:0)

foreach($all_projects as $KEY => $VALUE) {
  echo "KEY: $KEY - PRO_ID: {$VALUE['pro_id']}";
}

在您的情况下,您需要:

foreach ($all_projects as $project_id => $project) { 
  echo $project_id . " = " . $project['pro_id'];
}

答案 3 :(得分:0)

现在有了PHP5.5,你可以轻松地做到这一点:

foreach ($all_projects as list($id))
    echo $id;

旧方式:

foreach ($all_projects as $project)
    echo $project['pro_id'];

希望它能帮到你!

答案 4 :(得分:0)

如果我们以这种方式循环$all_projects foreach循环,

foreach ($all_projects as $key => $project) {
    echo($key);
}

然后$key实际上是0,1,等等,而不是7或20 - 正如您可能想要的那样 - 而$project将是项目的内容。

在你的情况下,我假设你想要的“项目ID”存储在“project”数组本身中,所以正如其他建议的那样,你应该写一些类似的东西

foreach($all_projects as $project) { // omitting the $key part since you don't need it
    echo($project['pro_id']);
}

这将打印实际的“项目ID”,即您想要的pro_id

如果您要改进此代码,可能需要以这种方式重新构建$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

然后您将能够使用原始代码循环:

foreach($all_projects as $project_id => $project) {
    echo($project_id);
}

$project_id为7,20等,$project为您项目的内容。

希望这能回答你的问题!