Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

When I loop through the given array, it suddenly sets back to the beginning:

Here it starts in a classes method:

$where = 'WHERE ';
array_walk( $columns, array( &$this, 'walker_cols' ), $where );

And this is the callback

function walker_cols( $item, $key, &$where )
{
    static $temp;
    if ( is_array( $item ) )
    {
        $temp = $key;
        array_walk( $item, array( __CLASS__, __FUNCTION__ ), $where );
    }

    var_dump($item);
    var_dump($where);

    return $where .= $temp ? "{$temp} = {$item} AND " : "{$key} = {$item} AND ";
}

The given Array:

$columns = array(
     'assoc_key_a' => 'assoc_val_a'
    ,'assoc_key_b' => array(
         0 => 'num_val_a'
        ,1 => 'num_val_b' 
     )
);

The desired output:

WHERE assoc_key_a = assoc_val_a AND assoc_key_b = num_val_a AND assoc_key_b = num_val_b

Now my result from the var_dump is the following:

input: "assoc_val_a"
output: "WHERE "

input: "num_val_a"
output: "WHERE assoc_key_a = assoc_val_a AND "

input: "num_val_b"
output: "WHERE assoc_key_a = assoc_val_a AND assoc_key_b = num_val_a AND "

input: {
    [0] => "num_val_a"
    [1] => "num_val_b"
}
output: "WHERE assoc_key_a = assoc_val_a     AND "

If there's another way to come to the desired output, I'd be happy to walk it. I already tried to do it with array_walk_recursive(), but with that function I wasn't able to get the assoc_key_b, because it directly jumped into the sub-array.

Thanks for any help. I'm pretty stuck.

share|improve this question
add comment

1 Answer 1

up vote 0 down vote accepted

Ok, the answer has been simple: I passed the reference on the wrong place.

Call:

$where = 'WHERE ';
array_walk( $columns, array( &$this, 'walker_cols' ), $where );

Callback:

function walker_cols( $item, $key, $where )
{
    static $temp;
    if ( is_array( $item ) )
    {
        $temp = $key;
        // reference to $where added here:
        array_walk( $item, array( &$this, __FUNCTION__ ), &$where );
    }

    var_dump($item);
    var_dump($where);

    return $where .= $temp ? "{$temp} = {$item} AND " : "{$key} = {$item} AND ";
}
share|improve this answer
    
Note: It could be that you have to ask if ( is_array( $item ) ) continue; a second time. When iterating through the array recursive it can be that you jump right out, so continue so far is the only option. –  kaiser Aug 30 '11 at 21:17
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.