Reputation: 23
I'm experimenting with a multidimensional array in PHP with strings as values. I want to echo all the values of one single column, instead of all values of all columns.
First i create the array!
$test = array
(
array("hoge", "bomen", "vangen"),
array("moeten", "we", "rekening"),
array("voor", "deze", "tijd")
); ``
This foreach outputs all the values!
foreach ($test as $val) {
echo "$val" . "<br/>";
}
How can i output only the values of column 2? instead of the values of all the columns.
I want this output:
bomen
we
deze
Upvotes: 0
Views: 3315
Reputation: 710
Try:
$test2 = array_map(
function($element){
return $element[0];
},
$test
);
$element[0]
is the element you want it from each array,
and do a foreach for $test2 or print inside closure.
Or use:
$arr = array_column($test, 0);
0
is the index key you want to keep. do a foreach on $arr.
Upvotes: 0
Reputation: 1828
Prints the value for the column number, which is set in the $column
variable.
<?php
$test = array(
array("hoge", "bomen", "vangen"),
array("moeten", "we", "rekening"),
array("voor", "deze", "tijd")
);
$column = 1; // number of the column you want
array_map(function($v) use ($column) {
echo $v[$column-1] . " ";
},$test);
?>
Upvotes: 0
Reputation: 59681
This should work for you:
$test = array(
array("hoge", "bomen", "vangen"),
array("moeten", "we", "rekening"),
array("voor", "deze", "tijd")
);
//vv Go trough each innerArray
foreach($test as $v)
echo $v[1] . "<br />";
//^^^^^ Print the second element of each innerArray
Output:
bomen
we
deze
Also for more information about arrays see the manual: http://php.net/manual/en/language.types.array.php (The manual is always a good reference to search for things and learn it :D)
Upvotes: 1
Reputation: 162
It depends what do you mean by column, but this is probably what you are looking for
$column = 0;
foreach ($test as $val) {
echo $val[$column];
}
Upvotes: 0
Reputation: 1502
This code can solve the problem:
$test = array
(
array("hoge", "bomen", "vangen"),
array("moeten", "we", "rekening"),
array("voor", "deze", "tijd")
);
for($i=0; $i<count($test);$i++) {
echo $test[$i][1];
}
If foreach is not your choice.
Upvotes: 0
Reputation: 3461
If you wanted to display the elements of the first inner array, then
foreach($test[0] as $value) echo $value."\n";
Upvotes: 0