2

Possible Duplicate:
Access array returned by a function in php

I have a function in a class which returns an array of data for a single item.

public function retrieveItemData($item_id) {

    $stmt   = parent::query("SELECT title FROM `item_main` WHERE `item_id` = $item_id");

    while($row = $stmt->fetch(PDO::FETCH_ASSOC)) :
        $item = array(
            'id' => $item_id,
            'title' => $row['title'],
            'url' => $item_id . '/' .$this->generate_seo_link( $row['title'], '-')
        );
    endwhile;

    return $item;
}

elsewhere in the class i call the function like so

$this->return .= '<td>' . $this->retrieveItemData($rep['source']) . '</td>';

$this->retrieveItemData($rep['source']) is obviously printing 'Array', how can i access the title key from here?

I have tried

$this->retrieveItemData($rep['source'])['title']

And

$this->retrieveItemData($rep['source'])->title

But with no luck.

Community
  • 1
  • 1
Vince Lowe
  • 3,521
  • 7
  • 36
  • 63
  • try to print_r, that way you can analyze the array better – raygo Sep 07 '12 at 15:47
  • My best guess without seeing the parent::query() function would be that fetch is returning a set of rows. Try `$this->retrieveItemData($rep['source'])[0]['title']`. Raygo is right. print_r will give you a good insight here. – tommarshall Sep 07 '12 at 15:50
  • i get syntax error, unexpected '[' if i do that @tommarshall – Vince Lowe Sep 07 '12 at 16:00

2 Answers2

2
$item_data = $this->retrieveItemData($rep['source']);

$item_data['title'];
Trevor
  • 6,659
  • 5
  • 35
  • 68
1

Array-access syntax on a function call: $this->retrieveItemData($rep['source'])['title'] is not possible until PHP 5.4.

In earlier versions, you have to use a temporary variable like in Trevor's answer. So you'd want to change the code where you call your function to:

$item_data = $this->retrieveItemData($rep['source']);
$this->return .= '<td>' . $item_data['title'] . '</td>';
Kenny Linsky
  • 1,726
  • 3
  • 17
  • 41