2

I spent over 2 hours looking for the solution, and I leave it to you because I am completely blocked. I try to learn the object in PHP. I created a function that return me the result of an SQL query.

Here is the var_dump return :

object(stdClass)[6]
  public 'name' => 
    array (size=2)
      0 => 
        object(stdClass)[11]
          public 'id' => string '1' (length=1)
      1 => 
        object(stdClass)[12]
          public 'id' => string '5' (length=1)

I used a foreach to parse this, but I don't get directly the id of each element. And I especially don't want to use another foreach.

foreach($function as $key => $value){
    var_dump($value->id);
}

But it doesn't work there.

Here is the function called who returns this result

public function nameFunction () {

    $obj = new stdClass();
    $return = array();

    $request = $this->getConnexion()->prepare('SELECT id FROM table') or die(mysqli_error($this->getConnexion()));

    $request->execute();
    $request->store_result();
    $request->bind_result($id);

    while ($request->fetch()) {
        $return[] = parent::parentFunction($id);
    }

    $obj->name = $return;

    $request-> close();

    return $obj;
}

And parent::parentFunction($id) returns :

object(stdClass)[11]
  public 'id' => string '1' (length=1)
2
  • 1
    Can you post the full code Commented Feb 11, 2015 at 9:33
  • Yes because we need to see if you are looping the array or the object Commented Feb 11, 2015 at 9:36

2 Answers 2

1

You are looping the object instead of array. Try to use this code

foreach($function->name as $key => $value){
    var_dump($value->id);
}

Tell me if it works for you

Sign up to request clarification or add additional context in comments.

1 Comment

Yeah !!!! That's it ! Woow. I knew I was not far, but I needed a little push. Beautiful, thank you!
0

This question might help you : php parsing multidimensional stdclass object with arrays

Especially answer from stasgrin

function loop($input)
{
    foreach ($input as $value)
    {
        if (is_array($value) || is_object($value))
            loop($value);
        else
        {
            //store data
            echo $value;
        }
    }
}

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.