打印数组值PHP

时间:2016-07-24 03:40:58

标签: php

我在尝试从数据库中打印某些值时遇到了一些问题。好的,我的数据库中有一个名为site_details的表,我保存了站点名称,电话和电子邮件。我有一个返回以下数组的查询:

Array
(
    [0] => Array
        (
            [text] => My Store
            [0] => My Store
            [column_key] => site_name
            [1] => site_name
        )

    [1] => Array
        (
            [text] => (123) 456 7890
            [0] => (123) 456 7890
            [column_key] => site_phone
            [1] => site_phone
        )

    [2] => Array
        (
            [text] => email@yahoo.com
            [0] => email@yahoo.com
            [column_key] => site_email
            [1] => site_email
        )

)

我想使用以下代码打印网站详细信息:

//Print out site name
//$site_details is the array being returned from the database
<?php echo $site_details['site_name']; ?>

返回

  

未定义的索引:site_name错误

。谁知道我怎么能这样做?非常感谢任何帮助。

更新

以下是我用来返回网站详细信息的代码:

Funtions.php

public function getSiteDetails(){
    global $pdo;

    $getDetails = $pdo->prepare("
        SELECT *
        FROM site_details
    ");
    $getDetails->execute();

    return $getDetails->fetchAll();
}

这是我调用函数的地方:

的index.php

require 'res/php/Functions.php';
$obj = new Functions();

//Get site details
$site_details = $obj->getSiteDetails();

数据库图片: Database Image

2 个答案:

答案 0 :(得分:1)

对于您给定的数组,printing机制如下: -

<?php

foreach($site_details as $site_detail){

   echo $site_detail['column_key'].' is:- '.$site_detail['text'];
}

?>

注意: - fetch_assoc将是更好的目标。

此外,每个列值都单独出现,这表示您在代码中执行了额外的操作,实际上并不需要

每个要打印的值的

: -

<?php echo $site_details[0]['text']; ?>

答案 1 :(得分:0)

使用提供数组的$getDetails>fetch(PDO::FETCH_ASSOC)

Array
(
    [0] => Array
        (
            [text] => My Store
            [column_key] => site_name
        )

    [1] => Array
        (
            [text] => (123) 456 7890
            [column_key] => site_phone
        )

    [2] => Array
        (
            [text] => email@y
            [column_key] => site_email
        )

)

然后使用,

echo $site_details['column_key'];