繁体   English   中英

使用php从数组中回显数据

[英]Echo datas from an array with php

我在php中有以下数组:

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

我需要回应这些值,所以我试试这个:

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

但我只有数值回应。

你有解决方案吗?

谢谢。

由于您使用的是foreach结构,因此$stat保存键, $data保存值。 所以说echo $stats[$stat]相当于回显具有键$stat 如果你想回应键,你应该这样做: echo $stat

在这里,您尝试打印数组的索引,

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

使用此代码打印数组的键

暂无
暂无

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

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