Ben Z.
Ben Z.

Reputation: 459

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?
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?

Upvotes: 0

Views: 99

Answers (5)

chihao
chihao

Reputation: 1

If we're looping through the $all_projects with foreach loop this way,

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.

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

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.

If you were to improve this code, you might want to restructure your $all_projects this way

$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.

Hope this answers your question!

Upvotes: 0

roptch
roptch

Reputation: 225

Now with PHP5.5, you have an easy way to do it:

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!

Upvotes: 0

Rob W
Rob W

Reputation: 9142

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'];
}

Upvotes: 0

Dave
Dave

Reputation: 1069

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'];
}

Upvotes: 0

Pitchinnate
Pitchinnate

Reputation: 7556

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

Upvotes: 3

Related Questions