-1

可能重复:
从数组中删除索引键以访问对象?

我需要能够访问该term_id值,但我不知道与数组关联的数字或索引。我怎样才能访问它?

我想像这样访问它$value->term_id,现在我需要通过将数字放在值($value->[26]->term_id)之后来访问它。

Array
(
    [26] => stdClass Object
        (
            [term_id] => 26
            [name] => Night Life.
            [slug] => shopping-and-night-life
            [term_group] => 0
            [term_taxonomy_id] => 28
            [taxonomy] => map_categories
            [description] => Most of the late night clubs, bars and pubs in Victoria are situated downtown. Here are a few to check out:
            [parent] => 0
            [count] => 6
            [object_id] => 925
        )

)
4

3 回答 3

4

您可以使用array_values()“重置”数组索引:

$new = array_values($old);

会导致

Array
(
    [0] => stdClass Object
        (
            [term_id] => 26
            [name] => Night Life.
            [slug] => shopping-and-night-life
            [term_group] => 0
            [term_taxonomy_id] => 28
            [taxonomy] => map_categories
            [description] => Most of the late night clubs, bars and pubs in Victoria are situated downtown. Here are a few to check out:
            [parent] => 0
            [count] => 6
            [object_id] => 925
        )

)

不管之前的数组索引是什么。

于 2012-12-07T14:05:22.927 回答
1

现在它是一个数组,因此您可以像这样访问它:$value[26]->term_id如果您不想放置密钥,您只需要设置另一个变量等于数组中的对象:

$value2 = $value[26];
echo $value2->term_id;

如果您不知道该值是否存在,请26使用 foreach。

foreach($value as $key => $val) {
     $term_id = $val->term_id;
}

如果你知道数组中只有一个元素,你可以这样做:

$value2 = end($value);
$term_id = $value2->term_id;
于 2012-12-07T14:03:35.043 回答
0

您必须要么搜索它,要么编写一个算法,使您一开始就不会丢失它。

于 2012-12-07T14:03:03.793 回答