【发布时间】:2013-08-25 20:35:23
【问题描述】:
我有一个名为 repeat 的函数。
如果数组键 == 'repeat',我想重复数组值
但是我的 if ($k == 'repeat') 比较失败了。
我的比较有什么问题?
function repeat($schema, $repeat = array()){
foreach($schema as $k => $v){
if($k == 'repeat')
第三行在重复函数中无法正常工作。
$schema = array(
array(
'tag' => 'div',
'class' => 'lines',
'repeat' => array(
'tag' => 'div',
array(
'tag' => 'span',
'style' => 'margin:10px; padding:10px',
'key' => 'title',
),
'key' => 'subject',
)
)
);
$repeat = array('Country Name' => 'Usa', 'City Name' => 'Newyork');
// Recursive String Replace - recursive_array_replace(mixed, mixed, array);
function recursive_array_replace($find, $replace, $array){
if (!is_array($array)){
return str_replace($find, $replace, $array);
}
$newArray = array();
foreach ($array as $key => $value) {
$newArray[$key] = recursive_array_replace($find, $replace, $value);
}
return $newArray;
}
function repeat($schema, $repeat = array()){
foreach($schema as $k => $v){
if($k == 'repeat'){
foreach($repeat as $rk => $rv){
$value = recursive_array_replace('title', $rk, $v);
$value = recursive_array_replace('subject', $rv, $value);
$info[] = $value;
}
}
}
//$schema = recursive_array_replace('repeat', $repeat, $schema);
return $info;
}
print_r(repeat($schema, $repeat));
更新1
架构可能是
$schema = array(
'tag' => 'div',
'class' => 'lines',
array(
'tag' => 'div',
'class' => 'lines',
'repeat' => array(
'tag' => 'div',
array(
'tag' => 'span',
'style' => 'margin:10px; padding:10px',
'key' => 'title',
),
'key' => 'subject',
array(
'tag' => 'span',
'style' => 'margin:10px; padding:10px',
'key' => 'title',
),
'key' => 'subject',
)
)
);
更新 2
$schema = array(
array(
'tag' => 'div',
'class' => 'lines',
array(
'tag' => 'div',
'repeat' => array(
'tag' => 'div',
array(
'tag' => 'span',
'style' => 'margin:10px; padding:10px',
'key' => 'title',
),
'key' => 'subject',
)
)
)
);
【问题讨论】:
-
您的
$schema是嵌套数组。你应该修改它或迭代foreachof$schema[0] -
$schema 没有固定值,总是可以改变的。 $schema[0] 可能会在其他情况下失败。我需要比较值的索引名称
-
您可以检查
is_array($schema[0]),如果为真,则将$schema(您的本地变量)分配给$schema[0]。 -
@Voitcus 在“重复”标签之前和之后可能有不同的数组 is_array 可能会失败。
-
我无法帮助您,因为我不知道您的意图。隔间失败是因为您的
$schema变量中没有“重复”键,但$schema[0]中存在一个。我没有测试您的代码的有效性(这就是为什么我不将其作为答案发布)
标签: php arrays multidimensional-array foreach compare