I have an array:
我有一个数组:
<?php
// My PHP version is 5.3.5
$arr = array("num"=>6,"book"=>"Polyanna","name"=>"Fred","age"=>8)
?>
How do I list the category's in the array and their values, to result something like this:
num: 6
book: Polyanna
name: Fred
age: 8
如何列出数组中的类别及其值,从而得到如下结果:num: 6书:Polyanna name: Fred age: 8
3 个解决方案
#1
4
First, you can't write arrays like that in PHP. You need to use this notation:
首先,不能用PHP编写这样的数组。你需要使用这个符号:
<?php
$arr = array('num' => 6, 'book' => 'Polyanna', 'name' => 'Fred', 'age' => 8);
?>
To list as you described, a foreach
loop will suffice:
如你所述,一个foreach循环就足够了:
<?php
$final_str = "";
foreach ( $arr as $key => $value ) {
$final_str .= $key . ": " . $value . "\n";
}
?>
Or, if you just need to echo
the data:
或者,如果您只需要回显数据:
<?php
foreach ( $arr as $key => $value ) {
echo $key . ": " . $value . "\n";
}
?>
#3
1
You need =>
instead of =
while declaring array
声明数组时需要=>而不是=
$arr = array("num"=>6,"book"=>"Polyanna","name"=>"Fred","age"=>8)
and iterate through foreach loop to retrieve values
遍历foreach循环以检索值
foreach ($arr as $key => $value)
{
echo $key. ":". $value;
}
#1
4
First, you can't write arrays like that in PHP. You need to use this notation:
首先,不能用PHP编写这样的数组。你需要使用这个符号:
<?php
$arr = array('num' => 6, 'book' => 'Polyanna', 'name' => 'Fred', 'age' => 8);
?>
To list as you described, a foreach
loop will suffice:
如你所述,一个foreach循环就足够了:
<?php
$final_str = "";
foreach ( $arr as $key => $value ) {
$final_str .= $key . ": " . $value . "\n";
}
?>
Or, if you just need to echo
the data:
或者,如果您只需要回显数据:
<?php
foreach ( $arr as $key => $value ) {
echo $key . ": " . $value . "\n";
}
?>
#2
#3
1
You need =>
instead of =
while declaring array
声明数组时需要=>而不是=
$arr = array("num"=>6,"book"=>"Polyanna","name"=>"Fred","age"=>8)
and iterate through foreach loop to retrieve values
遍历foreach循环以检索值
foreach ($arr as $key => $value)
{
echo $key. ":". $value;
}