1

Here's an example of an array that is returned by CakePHP's find() method:

Array 
(
    [Tutor] => Array 
    ( 
        [id] => 2 
        [PersonaId] => 1 
    ) 
)

The official documentation shows how to fetch records, but does not show how to iterate through them or even read out a single value. I'm kind of lost at this point. I'm trying to fetch the [id] value within the array. Here's what I've tried:

// $tutor is the array.
print_r($tutor[0]->id);

Notice (8): Undefined offset: 0 [APP\Controller\PersonasController.php, line 43]

Notice (8): Trying to get property of non-object [APP\Controller\PersonasController.php, line 43]

I've also tried:

// $tutor is the array.
print_r($tutor->id);

Notice (8): Trying to get property of non-object [APP\Controller\PersonasController.php, line 44]

2 Answers 2

1

The -> way of accessing properties is used in objects. What you have shown us is an array. In that example, accessing the id would require

$tutor['Tutor']['id']

Official PHP documentation, "Accessing array elements with square bracket syntax":

<?php
$array = array(
    "foo" => "bar",
    42    => 24,
    "multi" => array(
         "dimensional" => array(
             "array" => "foo"
         )
    )
);

var_dump($array["foo"]); //"bar"
var_dump($array[42]); //24
var_dump($array["multi"]["dimensional"]["array"]); //"foo"
?>
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks this helped. I went ahead and added some official PHP documentation and examples to further explain how it works.
0

The returned value is an array, not an object. This should work:

echo $tutor['Tutor']['id'];

Or:

foreach($tutor as $tut){
    echo $tut['Tutor']['id'] . '<br />';
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.