什么[]和[0]在数组的PHP中意味着什么?

时间:2014-04-28 14:56:03

标签: php

我正在使用wordpress,而我正在抓住自定义分类法,而我正在使用的代码是

$terms = get_the_terms($HeroID, 'hero-universe' );
foreach ( $terms as $term ) {
    $franchise_slug[] = $term->slug; // this grabs the hyphenated slug
    $franchise_name[] = $term->name; // this grabs the actual name
}

比显示我使用的自定义分类

<?php echo $franchise_name[0]; ?>

我想知道括号是什么,为什么我使用数字0?似乎如果我从$ franchise_name []和$ franchise_slug []中取出括号,它也能正常工作,那么它们的原因是什么?

谢谢。

2 个答案:

答案 0 :(得分:0)

[][0]与值数组一起使用...

$arr = array();

// add "blah" at the end of my array
$arr[] = "bla";
// add "niania" at the end of my array
$arr[] = "niania";

// output the first value of my array :
echo $arr[0]; // blah
// output the second value of my array :
echo $arr[1]; // niania

如果你使用一些foreach结构并且不知道什么是数组,那你将度过一段美好的时光......

Where are the non-trivial PHP-questions lately? ...

对Google的一点点搜索应该会给你答案。

答案 1 :(得分:0)

数组是值的集合。在PHP中,您可以为变量赋值:

$value = 1;

或在数组中添加一堆类似的值:

$programming_languages = ['PHP', 'C++', 'Ruby'];

要将我们的值打印到屏幕上会有所不同,因为我们的$value只保留1个实际值,我们可以将其反映到屏幕上:

echo $value; // prints 1

但由于我们的$programming_languages包含多个值,我们需要以不同的方式打印它。我们可以使用从0开始的索引访问每个值:

echo $programming_languages; // echos Array()

echo $programming_languages[0]; // echos 'PHP'

echo $programming_languages[1]; // echos 'C++'

$franchise_slug[] = $term->slug将值推送到数组的末尾,因此$franchise_slug是您的数组,并且您循环遍历所有条件,将每个slug添加到此数组的末尾。因此,使用上面的示例,我们可以使用索引0来访问第一个slug。