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 t开发者_StackOverflow社区o 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.
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 ";
}
精彩评论