当遇到逗号偏置的值对时,在2D数组中的反抛光行值

发布于 2025-02-01 01:24:14 字数 899 浏览 2 评论 0原文

这是我的2D数组:

Array
(
    [0] => Array
        (
            [id] => 9,5
            [item] => Item A, Item B
        )

    [1] => Array
        (
            [id] => 3
            [item] => Item C
        )
)

在第一行中,IDitem有逗号分隔的值。我想在新数组中将数据提取到单个值中,以便输出是这样的:

Array
(
    [0] => Array
        (
            [id] => 9
            [item] => Item A
        )

    [1] => Array
        (
            [id] => 3
            [item] => Item C
        )
    [2] => Array //new array 
        (
            [id] => 5
            [item] => Item B
        )
)

这是我当前的代码:

$arr = array();
foreach ($myarray as $val) {
    $arr[] = array(
        'id' => $val['id'],
        'item' => $val['item'],
    );
}
echo '<pre>', print_r($arr);

This is my 2d array:

Array
(
    [0] => Array
        (
            [id] => 9,5
            [item] => Item A, Item B
        )

    [1] => Array
        (
            [id] => 3
            [item] => Item C
        )
)

In the first row, there are comma-separated values for id and item. I want to extract the data into individual values in a new array so that the output is like this:

Array
(
    [0] => Array
        (
            [id] => 9
            [item] => Item A
        )

    [1] => Array
        (
            [id] => 3
            [item] => Item C
        )
    [2] => Array //new array 
        (
            [id] => 5
            [item] => Item B
        )
)

This is my current code:

$arr = array();
foreach ($myarray as $val) {
    $arr[] = array(
        'id' => $val['id'],
        'item' => $val['item'],
    );
}
echo '<pre>', print_r($arr);

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

触ぅ动初心 2025-02-08 01:24:14
$arr = [
    array(
        'id' => '9,5',
        'item' => 'Item A, Item B'
    ),
    array(
        'id' => 3,
        'item' => 'Item C'
    )
];

$newArr = array_reduce($arr, function($tmp, $ele){
    $arrIds = explode(',', $ele['id']);
    $arrItems = explode(',', $ele['item']);
    forEach($arrIds as $key => $arrId) {
        $tmp[] = array('id' => $arrId, 'item' => $arrItems[$key]);
    }
    return $tmp;
});
var_export($newArr);

输出:( demo

array (
  0 => 
  array (
    'id' => '9',
    'item' => 'Item A',
  ),
  1 => 
  array (
    'id' => '5',
    'item' => ' Item B',
  ),
  2 => 
  array (
    'id' => '3',
    'item' => 'Item C',
  ),
)
$arr = [
    array(
        'id' => '9,5',
        'item' => 'Item A, Item B'
    ),
    array(
        'id' => 3,
        'item' => 'Item C'
    )
];

$newArr = array_reduce($arr, function($tmp, $ele){
    $arrIds = explode(',', $ele['id']);
    $arrItems = explode(',', $ele['item']);
    forEach($arrIds as $key => $arrId) {
        $tmp[] = array('id' => $arrId, 'item' => $arrItems[$key]);
    }
    return $tmp;
});
var_export($newArr);

Output: (Demo)

array (
  0 => 
  array (
    'id' => '9',
    'item' => 'Item A',
  ),
  1 => 
  array (
    'id' => '5',
    'item' => ' Item B',
  ),
  2 => 
  array (
    'id' => '3',
    'item' => 'Item C',
  ),
)
若水微香 2025-02-08 01:24:14

下面的代码应完成工作。但是我不明白为什么您首先没有单独创建这些项目。

foreach ($arr as $i => $data) {
    if (!str_contains($data['id'], ',')) continue;

    $items = explode(',', $data['item']);

    foreach(explode(',', $data['id']) as $i => $id) {
        $new = ['id' => $ids[$i], 'item' => $items[$i]];

        if ($i) $arr[] = $new;
        else $arr[$i] = $new;
    }
}
var_export($arr);

输出:( demo

Warning: Undefined variable $ids

Warning: Trying to access array offset on null

Warning: Undefined variable $ids

Warning: Trying to access array offset on null
array (
  0 => 
  array (
    'id' => NULL,
    'item' => 'Item A',
  ),
  1 => 
  array (
    'id' => 3,
    'item' => 'Item C',
  ),
  2 => 
  array (
    'id' => NULL,
    'item' => ' Item B',
  ),
)

The code down below should do the job. But I didn't understand why you didn't create those items separately in the first place.

foreach ($arr as $i => $data) {
    if (!str_contains($data['id'], ',')) continue;

    $items = explode(',', $data['item']);

    foreach(explode(',', $data['id']) as $i => $id) {
        $new = ['id' => $ids[$i], 'item' => $items[$i]];

        if ($i) $arr[] = $new;
        else $arr[$i] = $new;
    }
}
var_export($arr);

Output: (Demo)

Warning: Undefined variable $ids

Warning: Trying to access array offset on null

Warning: Undefined variable $ids

Warning: Trying to access array offset on null
array (
  0 => 
  array (
    'id' => NULL,
    'item' => 'Item A',
  ),
  1 => 
  array (
    'id' => 3,
    'item' => 'Item C',
  ),
  2 => 
  array (
    'id' => NULL,
    'item' => ' Item B',
  ),
)
﹏半生如梦愿梦如真 2025-02-08 01:24:14

要将原始行值定为就地,然后随后遇到了界定值到数组的末尾,请使用foreach()并通过引用修改行以避免需要跟踪其索引。以下片段实际上将进行3次外循环的迭代,因为在循环完成之前将添加第一行的去溶解值作为新的第三行。

当没有发现逗号时,简短的爆炸过程可以改善片段的性能。

代码:( demo

foreach ($arr as &$row) {
    if (!str_contains($row['id'], ',')) {
        continue;  // do nothing to the row
    }
    $items = explode(',', $row['item']);
    foreach (explode(',', $row['id']) as $i => $id) {
        $new = ['id' => $id, 'item' => $items[$i]];
        if (!$i) {
            $row = $new;  // modify the original row
        } else {
            $arr[] = $new;  // append to end of original array
        }
    }
}
var_export($arr);

输出:

array (
  0 => 
  array (
    'id' => '9',
    'item' => 'Item A',
  ),
  1 => 
  array (
    'id' => 3,
    'item' => 'Item C',
  ),
  2 => 
  array (
    'id' => '5',
    'item' => ' Item B',
  ),
)

在遇到的逗号降低的值(不将它们附加到将它们附加到将它们附加到逗号)上结束),我可能会使用array_reduce()构建结果数组。 ( demo

var_export(
    array_reduce(
        $arr,
        function ($result, $row) {
            if (!str_contains($row['id'], ',')) {
                $result[] = $row;
            } else {
                array_push(
                    $result,
                    ...array_map(
                        fn($id, $item) => get_defined_vars(),
                        explode(',', $row['id']),
                        explode(',', $row['item'])
                    )
                );
            }
            return $result;
        },
        []
    )
);

输出:

array (
  0 => 
  array (
    'id' => '9',
    'item' => 'Item A',
  ),
  1 => 
  array (
    'id' => '5',
    'item' => ' Item B',
  ),
  2 => 
  array (
    'id' => 3,
    'item' => 'Item C',
  ),
)

To modify the original row values in-place and append subsequently encountered delimited values to the end of the array, use a foreach() and modify the rows by reference to avoid needing to track their index. The following snippet will actually make 3 iterations of the outer loop because the deconsolidated values from the first row will be added as a new third row before the loop finishes.

Short circuiting the exploding process when there are no commas found improves the performance of the snippet.

Code: (Demo)

foreach ($arr as &$row) {
    if (!str_contains($row['id'], ',')) {
        continue;  // do nothing to the row
    }
    $items = explode(',', $row['item']);
    foreach (explode(',', $row['id']) as $i => $id) {
        $new = ['id' => $id, 'item' => $items[$i]];
        if (!$i) {
            $row = $new;  // modify the original row
        } else {
            $arr[] = $new;  // append to end of original array
        }
    }
}
var_export($arr);

Output:

array (
  0 => 
  array (
    'id' => '9',
    'item' => 'Item A',
  ),
  1 => 
  array (
    'id' => 3,
    'item' => 'Item C',
  ),
  2 => 
  array (
    'id' => '5',
    'item' => ' Item B',
  ),
)

To deconsolidate the comma-delimited values as they are encountered (not appending them to the end), I might use array_reduce() to build the result array. (Demo)

var_export(
    array_reduce(
        $arr,
        function ($result, $row) {
            if (!str_contains($row['id'], ',')) {
                $result[] = $row;
            } else {
                array_push(
                    $result,
                    ...array_map(
                        fn($id, $item) => get_defined_vars(),
                        explode(',', $row['id']),
                        explode(',', $row['item'])
                    )
                );
            }
            return $result;
        },
        []
    )
);

Output:

array (
  0 => 
  array (
    'id' => '9',
    'item' => 'Item A',
  ),
  1 => 
  array (
    'id' => '5',
    'item' => ' Item B',
  ),
  2 => 
  array (
    'id' => 3,
    'item' => 'Item C',
  ),
)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文