使用id从数组中获取标题

时间:2012-06-02 15:41:45

标签: php

Probaly是一个简单的一个,但我有以下数组,其中包含数据库中的所有类别:

Array
(
    [0] => Array
        (
            [id] => 1
            [title] => Fitness News
            [description] => Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin tincidunt tempor nunc, sit amet facilisis metus molestie nec. Nulla varius justo et felis euismod bibendum. Vestibulum suscipit tempus viverra. Mauris eros lorem, posuere eget mattis et, euismod id metus. In ac dignissim ligula. fdsfdsfdsfds fdsf fsd
            [image1] => test
            [image1_title] => test
            [created] => 2012-03-26
        )

    [1] => Array
        (
            [id] => 2
            [title] => Recommended Products
            [description] => Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin tincidunt tempor nunc, sit amet facilisis metus molestie nec. Nulla varius justo et felis euismod bibendum. Vestibulum suscipit tempus viverra. Mauris eros lorem, posuere eget mattis et, euismod id metus. In ac dignissim ligula.gdsfdsfdsfdsfds
            [image1] => H
            [image1_title] => H
            [created] => 2012-03-25
        )

    [2] => Array
        (
            [id] => 3
            [title] => New Category
            [description] => This is a new category
            [image1] => 
            [image1_title] => 
            [created] => 2012-03-13
        )

)

现在我所拥有的是一个类别ID,但是我希望从上面的数组获得类别标题。

3 个答案:

答案 0 :(得分:0)

$key = array_search ($category_id, $array);
echo $array [$key] ['title'];

$category_id = 1;
foreach ($array as $val) {
    if ($val ['id'] == $category_id) {
        $title = $val ['title'];
        break;
    }
}
echo $title

答案 1 :(得分:0)

$key = array_search($categoryId, $array);
$title = $array[$key]['title'];

答案 2 :(得分:0)

我没有搜索旧数组,而是重新格式化旧数组,以便它更有用:

$categories = array();

foreach( $old_categories as $item)
    $categories[ $item['id'] ] = $item;

现在,您可以根据ID访问任何需要的内容。例如:

$id = 2;
echo $categories[ $id ]['title'];
echo $categories[ $id ]['description'];