簡體   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