0

I passed $data array to view. $data array is like:

$data = array('t0' => array('point' => 0), 't1' => array('point' => 2) .... );

What I am trying to do is using this array in my view as follows:

<?php echo $t0['point']; ?> //It works!

But I am doing this in a for loop by definition of structure. Therefore I need to pass numeric value(near 't' letter) as a variable. How can I achieve this?

2 Answers 2

1

you can do like this:

$count = count($data);   //if you know the count of $data
 for($i = 0; $i < $count; $i++) {
        $var = 't'.$i;
        echo ${$var}['point'];
    }
Sign up to request clarification or add additional context in comments.

Comments

1

You'll need to send through a count in your data, so you can later run a loop, so change your $data array to something like:

$data = array('tCount' => 10, 't0' => array('point' => 0), 't1' => array('point' => 2) .... );

Note the addition of the tCount variable in the array, that should tell how many t items you are sending in the array, we'll use that in the loop below.

Now you can use a variable variable, something like:

foreach ($i = 0; $i < $tCount); $i++) {
    $key = 't' . $i;
    echo($$key['point']);
}

Note the use of the double $

2 Comments

I am getting the error: Message: Illegal string offset 'point'.
made an edit to ensure you send a tCount to your view, otherwise there's no way of knowing how many times to loop through

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.