[英]Display array values in PHP
So, I'm working with PHP for the first time and I am trying to retrieve and display the values of an array. 因此,我是第一次使用PHP,并且试图检索和显示数组的值。 After a lot of googling, the only methods I can find for this are
print_r
, var_dump
or var_export
. 经过大量的搜索之后,我只能找到的方法是
print_r
, var_dump
或var_export
。 However, all of these methods return something that looks like this: 但是,所有这些方法都返回如下所示的内容:
[a] => apple
[b] => banana
[c] => orange
I can't figure out how to style this outout. 我不知道如何设计这种风格。 I need to strip away the
[a] =>
part and add commas. 我需要删除
[a] =>
部分并添加逗号。 I know this must be a pretty straightforward process but I haven't been able to track down any documentation that demonstrates how to do it. 我知道这肯定是一个非常简单的过程,但是我无法找到任何演示如何执行此操作的文档。
There is foreach loop in php. php中有foreach循环。 You have to traverse the array.
您必须遍历数组。
foreach($array as $key => $value)
{
echo $key." has the value". $value;
}
If you simply want to add commas between values, consider using implode 如果只想在值之间添加逗号,请考虑使用implode
$string=implode(",",$array);
echo $string;
<?php $data = array('a'=>'apple','b'=>'banana','c'=>'orange');?>
<pre><?php print_r($data); ?></pre>
Result: 结果:
Array 数组
( (
[a] => apple [a] =>苹果
[b] => banana [b] =>香蕉
[c] => orange [c] =>橙色
) )
You can use implode to return your array with a string separator. 您可以使用implode返回带有字符串分隔符的数组。
$withComma = implode(",", $array);
echo $withComma;
// Will display apple,banana,orange
use implode(',', $array);
使用
implode(',', $array);
for output as apple,banana,orange
用于输出为
apple,banana,orange
Or 要么
foreach($array as $key => $value)
{
echo $key." is ". $value;
}
a simple code snippet that i prepared, hope it will be usefull for you; 我准备的一个简单的代码段,希望对您有用;
$ages = array("Kerem"=>"35","Ahmet"=>"65","Talip"=>"62","Kamil"=>"60");
reset($ages);
for ($i=0; $i < count($ages); $i++){
echo "Key : " . key($ages) . " Value : " . current($ages) . "<br>";
next($ages);
}
reset($ages);
Iterate over the array and do whatever you want with the individual values. 遍历数组,并对各个值进行任何所需的操作。
foreach ($array as $key => $value) {
echo $key . ' contains ' . $value . '<br/>';
}
you can easily use join() 您可以轻松使用join()
$fruits = array("apple", "banana", "orange");
print join(" ".$fruits);
Other option: 其他选择:
$lijst=array(6,4,7,2,1,8,9,5,0,3);
for($i=0;$i<10;$i++){
echo $lijst[$i];
echo "<br>";
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.