【发布时间】:2014-01-01 00:53:10
【问题描述】:
我正在尝试删除数组键名称中的所有空格,即 str_replace(' ','',$value) (或者最坏的情况下用下划线 (_) 替换它们)
我正在尝试在我的多维数组的最深层(如下所示)执行此操作(因为其他层/级别没有空格(感谢上帝!))
[...]
[ownPagestoriesbystorytype] => Array
(
[type] => pagestoriesbystorytype
[object_id] => 12365478954
[metric] => page_stories_by_story_type
[end_time] => 1386057600
[period] => 86400
[ownValues] => Array
(
[type] => pagestoriesbystorytypemetrics
[fan] => 1913
[page post] => 153
[user post] => 24
)
)
[ownPagestorytellersbystorytype] => Array
(
[type] => pagestorytellersbystorytype
[object_id] => 12365478954
[metric] => page_storytellers_by_story_type
[end_time] => 1386057600
[period] => 86400
[ownValues] => Array
(
[type] => pagestorytellersbystorytypemetrics
[fan] => 1902
[page post] => 137
[user post] => 9
)
)
[...]
到目前为止,我的尝试都没有结果:
[...]
if (is_array($value))
{
$keys = str_replace(' ','',array_keys($value));
$values = array_values($value);
$value = array_combine($keys,$values);
}
[...]
[...]
foreach ($value as $k => $v)
{
$b = str_replace(' ','',$k);
$value[$b] = $value[$k];
unset ($value[$k]);
}
[...]
上面的代码不起作用,但是如果我把 print_r($value);在循环结束时,您可以清楚地看到空格正在被删除,只是最终结果以空格结尾(STILL)。
整个循环是这样的:
for ($i=0;$i<count($results);$i++)
{
for ($j=0;$j<count($results[$i]);$j++)
{
foreach($results[$i][$j] as $key => $value)
{
$typee = ['type' => strtolower(str_replace('_','',$results[$i][$j]['metric']))];
array_insert($results[$i][$j],$typee,0);
if (is_array($value))
{
$keys = str_replace(' ','',array_keys($value));
$values = array_values($value);
$value = array_combine($keys,$values);
$type = ['type' => strtolower(str_replace('_','',$results[$i][$j]['metric']))."metrics"];
array_insert($results[$i][$j]['value'],$type,0);
$results[$i][$j]['ownValues'] = $results[$i][$j][$key];
unset($results[$i][$j][$key]);
}
}
}
}
你可以在这里看到整个数组的样子:
How to prepend array to each element of another array with my choice of key and value (in php)?
有什么建议吗? :)
【问题讨论】:
标签: php arrays loops multidimensional-array foreach