从数组中删除索引

时间:2012-12-07 14:00:04

标签: php arrays

  

可能重复:
  Remove index key from Array for accessing to object?

我需要能够访问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
        )

)

3 个答案:

答案 0 :(得分: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
        )

)

无论前面的数组索引是什么。

答案 1 :(得分: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;

答案 2 :(得分:0)

你必须要搜索它写一个算法,你不会丢失它。