1

I have listed an example below. What I need is for $key to return the actual index number (position) in the array during the loop, but instead it is returning Array. The same code works fine when given a single dimension array, but not in the example below.

GIVEN:

$screenshots would be similar to the following with only more entries.

Array
(
    [0] => Array
        (
            [screenshot_id] => 871
            [image_filename] => DSCF0124.JPG
        )

)

PHP:

//build in clause & binding using selected array from above
$prefix = $in_clause = '';
$binding_clause = array();  
foreach($screenshots as $key)
{
    $in_clause .= $prefix.':selected_'.$key;
    $prefix = ', ';
    $binding_clause[':selected_'.$key] = $key['screenshot_id'];
}

RESULT:

$inclause = :selected_Array

$binding_clause = 

Array
(
    [:selected_Array] => 871
)

EXPECTED:

$inclause = :selected_0

$binding_clause = 

Array
(
    [:selected_0] => 871
)

4 Answers 4

2

Just because you call it $key doesn't make it a key. You need the key and the value (inner array):

foreach($screenshots as $key => $value)
{
    $in_clause .= $prefix.':selected_'.$key;
    $prefix = ', ';
    $binding_clause[':selected_'.$key] = $value['screenshot_id'];
}
Sign up to request clarification or add additional context in comments.

Comments

1

You need to tell it that you want the KEY and the VALUE.

like this:

foreach($screenshots as $key=>$screenShot)

That will get you the key and the value.

Comments

1

You just need to change your foreach to cast keys and values

foreach($screenshots as $key => $val)

Now the key is in your $key variable while you can access elements with $val array, for example $key['screenshot_id']

You can have a check to documentation examples here

Comments

1

Try:

foreach($screenshots as $key => $screenshot)
{
    $in_clause .= $prefix.':selected_'.$key;
    $prefix = ', ';
    $binding_clause[':selected_'.$key] = $screenshot['screenshot_id'];
}

Read more about PHP foreach: http://php.net/manual/en/control-structures.foreach.php

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.