此代码:
for ($p=0;$p<count($results);$p++){
foreach ($results[$p] as $k => $v){
$typeee = ['type' => strtolower(str_replace('_','',$results[$p][$k]['metric']))."container"];
array_insert2($results[$p],0,$typeee);
}
}
print_r($results);
给了我这个:
Array (
[0] => Array
(
[type] => pagestoriescontainer
[0] => Array
(
[type] => pagestories
[object_id] => 123456778
[metric] => page_stories
[end_time] => 1386057600
[period] => 86400
[value] => 2090
)
[1] => Array
(
[type] => pagestorytellers
[object_id] => 123456778
[metric] => page_storytellers
[end_time] => 1386057600
[period] => 86400
[value] => 2041
)
[...]
[1] => Array
(
[0] => Array
(
[type] => pagestories
[object_id] => 199193463123456778
[metric] => page_stories
[end_time] => 1386057600
[period] => 86400
[value] => 0
)
[1] => Array
(
[type] => pagestorytellers
[object_id] => 199193463123456778
[metric] => page_storytellers
[end_time] => 1386057600
[period] => 86400
[value] => 0
)
[...]
但是这段代码:
for ($p=0;$p<count($results);$p++){
foreach ($results[$p] as $k => $v){
$typeee = ['type' => strtolower(str_replace('_','',$results[$p][$k]['metric']))."container"];
array_insert2($results[$p],$k,$typeee);
}
}
不要给我这个:
Array (
[0] => Array
(
[type] => pagestoriescontainer
[0] => Array
(
[type] => pagestories
[object_id] => 123456778
[metric] => page_stories
[end_time] => 1386057600
[period] => 86400
[value] => 2090
)
[type] => pagestorytellerscontainer
[1] => Array
(
[type] => pagestorytellers
[object_id] => 123456778
[metric] => page_storytellers
[end_time] => 1386057600
[period] => 86400
[value] => 2041
)
[...]
[1] => Array
(
[type] => pagestoriescontainer
[0] => Array
(
[type] => pagestories
[object_id] => 199193463123456778
[metric] => page_stories
[end_time] => 1386057600
[period] => 86400
[value] => 0
)
[type] => pagestorytellerscontainer
[1] => Array
(
[type] => pagestorytellers
[object_id] => 199193463123456778
[metric] => page_storytellers
[end_time] => 1386057600
[period] => 86400
[value] => 0
)
[...]
为什么呢?我怎样才能得到我想要的东西? :)
此外,
function array_insert2 (&$array, $position, $insert_array) {
$first_array = array_splice ($array, 0, $position);
$array = array_merge ($first_array, $insert_array, $array);
}
答案 0 :(得分:1)
array_insert2的第二个参数是位置。在第一个代码中,您实际上给它一个整数,使其成为有效位置($ p,与array_splice函数结合)。 在第二段代码中,提供给array_insert2的位置是来自$ results [$ p]的foreach循环的键($ k)。给定的密钥无法与array_splice函数一起使用。也许不是提供$ k,而是在$ results [$ p]中给出$ k的array_search结果。
短答案: 第二段代码中提供的位置不是整数,因此不能用于array_splice函数。