2

I have this object containing one row and many keys/variables with numbered names. I need to pass each of them one at a time to another function. How do I loop through the keys instead of the rows?

The code would look like this:

foreach ($object['id'] as $row):
$i++;
$data['myInfo'][$i] = $this->get_data->getInfo('data1', 'id', $row->{'info'.$i.'_id'});`

but this obviously won't work since it's looping through the rows/instances of an object, and I have only one row in my $object['id'] object (with info1_id, info2_id, info3_id, info4_id... etc keys), so the loop stops after just one cycle. And I really don't feel like typing all of that extra code by hand, there's gotta be solution for this. :)

3
  • foreach ($object['id'] as $KEY=>$row){ Commented May 23, 2015 at 23:47
  • that's a single cycle and doesn't solve anything. I would still need to type everything (a lot) by hand. Please do read again. Commented May 23, 2015 at 23:49
  • There are no "rows" in arrays. You have dimensions, keys and values. Commented May 24, 2015 at 0:44

2 Answers 2

1

You can just iterate through your object like an array :

foreach ($object['id'] as $row) {

    foreach ($row as $k => $v) {
        $id = substr($k, 4, strpos($k, '_')-4);
        $data['myInfo'][$id] = $this->get_data->getInfo('data1', 'id', $v);`
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

Thanks for the directions Alfwed, I didn't know you could use foreach loop for anything other than instances of an object or arrays (only started learning php a week or so ago), but now it looks pretty straight forward. that's how I did it:

foreach ($object['id'] as $row):

        foreach ($row as $k=>$v): 
             $i++;
            if ($k == print_r ('info'.$i.'_id',true)){


            $data['myinfo'][$i] = $this->get_db->getRow('products', 'id','info'.$i.'_id'); 

    <...>

in my case, I knew how many and where were those values, so I didn't have to worry about index values too much.

1 Comment

$row here is an object

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.