DemCodeLines
DemCodeLines

Reputation: 1920

Storing values of multidimensional array into variables

I have the following code:

$res = $db->getArticles($db);
$hey = print_r($res, TRUE);
echo $hey['0'];

Here is the code for $db->getArticles:

public function getArticles() {
    $array = array();
    try {
        $sth = $this->db->prepare("SELECT * FROM posts ORDER BY id");
        $sth->execute();
        foreach ($sth->fetchAll(PDO::FETCH_ASSOC) as $row) {
            $array[] = $row;
        }
        return $array;
    } catch (Exception $e) {

    }
}

The logic is that the function queries the database and puts everything into an array. The number of rows in the table will always be pretty low, so performance isn't an issue.

The following is the output of the first code snippet above:

echo $hey['0']; // prints "A" (without the quotes).
echo $hey['1']; // prints "r"
echo $hey['2']; // prints "r"
echo $hey['3']; // prints "a"
echo $hey['4']; // prints "y"

As you can see, it spells out the word "Array."

echo $hey prints the following:

Array ( [0] => Array ( [id] => 1 [author] => 0 [content] => This Is a Test [publication_date] => 1380380992 ) )

My end goal is to store each individual value into a variable and do something with it. This would all happen inside a for loop which runs on the array so I can get information from each row.

What am I doing wrong?

Upvotes: 0

Views: 3090

Answers (2)

Nick Rolando
Nick Rolando

Reputation: 26177

$hey = print_r($res, TRUE);

This will return a string that gives the info of the array $res. If you echo it, you should expect to see the same as what print_r($res); displays, as you've shown. $res is already an array of your query data, so loop over that.

foreach($res as $row) {  //row loop
  foreach($row as $col) {  //column loop
    //do something
  }
}

Upvotes: 1

Joran Den Houting
Joran Den Houting

Reputation: 3163

$array = array( array( ID => 1, 
                  author => 0,
                  content => "This Is a Test",
          publication_date => 1380380992
                )
         );



echo $array['0']['author'];

This works for me...

just echo echo $array['0']['author']; and replace author by the field you need.

Upvotes: 0

Related Questions