通过递归函数混合数组到字符串
当我循环给定的数组时,它突然回到开头:
这里它从一个类方法开始:
$where = 'WHERE ';
array_walk( $columns, array( &$this, 'walker_cols' ), $where );
这是回调
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 ";
}
给定的数组:
$columns = array(
'assoc_key_a' => 'assoc_val_a'
,'assoc_key_b' => array(
0 => 'num_val_a'
,1 => 'num_val_b'
)
);
所需的输出:
WHERE assoc_key_a = assoc_val_a AND assoc_key_b = num_val_a AND assoc_key_b = num_val_b
现在我的结果是< code>var_dump 如下:
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 "
如果有其他方法可以达到所需的输出,我很乐意使用它。我已经尝试使用 array_walk_recursive() 来完成此操作,但是使用该函数我无法获取 assoc_key_b ,因为它直接跳转到子数组中。
感谢您的任何帮助。 我陷入了困境。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
好吧,答案很简单:我将参考文献传递到了错误的地方。
呼叫:
回拨:
Ok, the answer has been simple: I passed the reference on the wrong place.
Call:
Callback: