1

对你来说可能很简单,但我有以下数组,其中包含数据库中的所有类别:

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,但我想从上面的数组中获取类别标题。

4

3 回答 3

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
于 2012-06-02T15:46:01.723 回答
0
$key = array_search($categoryId, $array);
$title = $array[$key]['title'];
于 2012-06-02T15:46:09.840 回答
0

我不会搜索旧数组,而是重新格式化旧数组,这样它就更有用了:

$categories = array();

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

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

$id = 2;
echo $categories[ $id ]['title'];
echo $categories[ $id ]['description'];
于 2012-06-02T15:46:50.193 回答