2016-07-24 133 views
1

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

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 protected] 
      [0] => [email protected] 
      [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(); 
} 

这就是我所说的功能:

指数。 php

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

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

数据库图像: Database Image

+0

您向我们展示的数组没有密钥“site_name”,因此底部的代码不会回显任何有用的内容。告诉我们你想要什么样的输出,基于上面的 – BeetleJuice

+0

的站点详细信息,你可以打印出你的数组中存在的索引,例如'<?php echo $ site_details [0] ['text']; ?>等 –

+0

请在您的代码中写下您的查询。我想你可能在这里使用了fetch_array。 fetch_assoc将是最好的选择。 –

回答

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']; ?> 
+0

感谢您的回答,但是如何在循环外打印每个值。我不想一次打印全部。 –

+0

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

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 protected] 
      [column_key] => site_email 
     ) 

) 

然后你se,

echo $site_details['column_key'];