php 将列中的每个值移动到二维数组中的下一行

dojqjjoe  于 2023-06-04  发布在  PHP
关注(0)|答案(4)|浏览(474)

下面是一个例子:

foreach ($something as $key => $row)
{
    $output[] = ["name" => $row["name"], "points" => $row["points"]];
}
print_r($output);

这将生成以下数组:

[
    ['name' => 'Mark', 'points' => 1],
    ['name' => 'Sara', 'points' => 2],
    ['name' => 'Jack', 'points' => 3],
]

我尝试将**$row[“points”]**移动到下一行,以获得以下输出:

[
    ['name' => 'Mark', 'points' => null],
    ['name' => 'Sara', 'points' => 1],
    ['name' => 'Jack', 'points' => 2],
]

我不在乎是否有一些数据丢失,或者我的**[points] => 3是否进入新数组。我只需要以编程方式将$row[“points”]始终移动到下一个元素。我正在使用next()函数,但没有成功,而且我确信我无法使用$key+1**来实现结果。
有没有可能在我构建数组的时候把它放在上面,或者我必须在以后用一个单独的函数移动元素?

42fyovps

42fyovps1#

$output = array();
$point = '';
foreach($something AS $key => $row)
{
    $output[$key] = array("name"=>$row["name"], "points"=>$point);
    $point = $row['points'];
}
print_r($output);
jtw3ybtb

jtw3ybtb2#

foreach($something AS $key => $row)
{
    $output[$key]['name']       = $row["name"];
    $output[$key+1]['points']   = $row["points"];
}
print_r($output);
z5btuh9x

z5btuh9x3#

1.前向遍历索引数组以生成新数组:(Demo

$result = [];
foreach ($something as $i => $row) {
    $row['points'] = $something[$i - 1]['points'] ?? '';
    $result[] = $row;
}
var_export($result);

或:(Demo

$result = [];
foreach ($something as $i => $row) {
    $result[] = array_replace(
        $row,
        ['points' => $something[$i - 1]['points'] ?? '']
    );
}
var_export($result);

1.反向遍历索引数组以修改输入数组:(Demo

for ($i = array_key_last($something); $i >= 0; --$i) {
    $something[$i]['points'] = $something[$i - 1]['points'] ?? '';
}
var_export($something);

1.向前遍历关联数组以生成新数组,而无需单独声明每个元素:(Demo

$result = [];
$points = null;
foreach ($something as $key => $row) {
    $result[$key] = array_replace($row, ['points' => $points]);
    $points = $row['points'];
}
var_export($result);
cdmah0mi

cdmah0mi4#

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);

相关问题