请参阅我用于构建数组的附加示例
foreach($something AS $key => $row)
{
$output[] = array("name"=>$row["name"], "points"=>$row["points"]);
}
print_r($output);
这是输出:
Array
(
[0] => Array
(
[name] => Mark
[points] => 1
)
[1] => Array
(
[name] => Sara
[points] => 2
)
[2] => Array
(
[name] => Jack
[points] => 3
)
)
我要做的是将 $ row [“points”] 移动到下一个数组元素以获取此输出:
Array
(
[0] => Array
(
[name] => Mark
[points] =>
)
[1] => Array
(
[name] => Sara
[points] => 1
)
[2] => Array
(
[name] => Jack
[points] => 2
)
)
我不在乎是否有一些数据丢失或者我的 [points] => 3 进入一个新阵列。我只需要以编程方式将 $ row [“points”] 始终移至下一个元素。我正在玩 next()功能但没有成功,还有 $ key + 1 ,我确信我无法用它来实现结果。
在我构建数组时是否有可能将它放在顶部或者我以后用一个单独的函数强制移动元素?换句话说,你会做什么?
答案 0 :(得分:1)
Try This:
$output = array();
$something = array(
'0' => array(
'name' => 'Mark',
'points' => 1,
),
'1' => array(
'name' => 'Sara',
'points' => 2,
),
'2' => array(
'name' => 'Jack',
'points' => 3,
)
);
$point = '';
foreach($something AS $key => $row)
{
$output[$key] = array("name"=>$row["name"], "points"=>$point);
$point = $row['points'];
}
echo '<pre>';
print_r($output);
答案 1 :(得分:0)
尝试它是否有帮助:
foreach($something AS $key => $row)
{
$output[$key]['name'] = $row["name"];
$output[$key+1]['points'] = $row["points"];
}
print_r($output);
答案 2 :(得分:0)
使用:
foreach($array as $key => $each)
{
$array[0]['points'] = "";
$array[$key]['name'] = $each["name"];
if(isset($array[$key+1])) $array[$key+1]['points'] = $each["points"];
}
print_r($array);