如何从数组php打印数据?

时间:2013-05-22 22:12:46

标签: php arrays

我在调用php数组中的正确值时遇到了一些麻烦。这是阵列。

Array ( [count] => 1 [threads] => Array ( [13] => Array ( [thread_id] => 13 [node_id] => 4 [title] => Forum Integration nearly complete! [reply_count] => 0 [view_count] => 0 [user_id] => 59 [username] => Faeron [post_date] => 1369257302 [sticky] => 0 [discussion_state] => visible [discussion_open] => 1 [discussion_type] => [first_post_id] => 23 [first_post_likes] => 0 [last_post_date] => 1369257302 [last_post_id] => 23 [last_post_user_id] => 59 [last_post_username] => Faeron [prefix_id] => 1 [content] => Array ( [count] => 1 [content] => Array ( [23] => Array ( [post_id] => 23 [thread_id] => 13 [user_id] => 59 [username] => Faeron [post_date] => 1369257302 [message] => It's been quite a while since we began to integrate the phanime Forums with the main site. We have now finished the integration with the phanime Forums and the main site. You will no longer notice that there are two platforms running phanime, but instead only one. Our next step is to theme the forums to make it look like the main site! [ip_id] => 268 [message_state] => visible [attach_count] => 0 [position] => 0 [likes] => 0 [like_users] => a:0:{} [warning_id] => 0 [warning_message] => ) ) ) ) ) )

现在让我们说这个数组命名为$array然后得到第一个元素的值" [count]"我不能说以下内容:print $array["[count]"]< - 这会返回错误。

具有值作为数组本身的元素,即[threads]元素。我怎么得到,也许是[thread_id]元素的价值?

2 个答案:

答案 0 :(得分:1)

像这样使用:

echo $array['count']; // would output '1'
echo $array['threads'][13]['thread_id']; // outputs '13'
echo $array['threads'][13]['content']['content'][23]['message']; // "It's been.."

以下是有关多维数组的(简要)文档:http://php.net/manual/en/language.types.array.php#language.types.array.syntax.accessing

以下是一个很好的指南:http://www.developerdrive.com/2012/01/php-arrays-array-functions-and-multidimensional-arrays/

更新:要在不事先知道编号数组键的情况下获取'message'的值,您可以使用:

reset($array);
$first = array_keys($array['threads']);
$first = $first[0];
$second = array_keys($array['threads'][$first]['content']['content']);
$second = $second[0];
echo $array['threads'][$first]['content']['content'][$second]['message']; 

答案 1 :(得分:0)

您可以使用以下方法访问数组中的值:

echo $array['count'];

你也可以像这样打印整个数组:

print_r($array);

var_dump($array);

如果要从多维数组中写入值,请使用以下命令:

echo $array[23]['post_id'];

总而言之,请参阅以下内容:

$array = array(
    'bar'  => 'testing value',
    'foo'  => array(
         'bar' => 'test'
    )
);

print_r($array) // Will print whole array
echo $array['bar']; // Will print 'testing value'
print_r($array['foo']); // Will print the second level array
echo $array['foo']['bar']; // Will print 'test'