简体   繁体   English

使用php从数组中回显数据

[英]Echo datas from an array with php

I have the following array in php: 我在php中有以下数组:

$stats = array(
    "Item 1"    =>   20,
    "Item 2"    =>   30,
    "Item 3"    =>   66,
    "Item 4"    =>   1
);

I need to echo these values, so I try this: 我需要回应这些值,所以我试试这个:

<?
    foreach ($stats as $stat => $data) {
        echo '
            <div class="col-sm-6">
                <div class="widget">
                    <div class="widget-body p-t-lg">
                        <div class="clearfix m-b-md">
                            <h1 class="pull-left text-primary m-0 fw-500"><span class="counter" data-plugin="counterUp">'.$data.'</span></h1>
                            <div class="pull-right watermark"><i class="fa fa-2x fa-tv"></i></div>
                        </div>
                        <p class="m-b-0 text-muted">'.$stats[$stat].'</p>
                    </div>
                </div>
            </div>
        ';
    }
?>

But I have only the numerical values echoed. 但我只有数值回应。

Do you have the solution ? 你有解决方案吗?

Thanks. 谢谢。

Since you are using the foreach construct, $stat holds the keys and $data holds the values. 由于您使用的是foreach结构,因此$stat保存键, $data保存值。 So when saying echo $stats[$stat] is equivalent to echoing the value that has the key $stat . 所以说echo $stats[$stat]相当于回显具有键$stat If you want to echo the keys you should do this : echo $stat . 如果你想回应键,你应该这样做: echo $stat

Here you are trying to print the index of the array, 在这里,您尝试打印数组的索引,

$array = array(0 => 'blue', 1 => 'red', 2 => 'green', 3 => 'red');
$key = array_search('green', $array); // $key = 2;
echo $key;

Use this code to print the key of the array 使用此代码打印数组的键

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM