当遇到逗号偏置的值对时,在2D数组中的反抛光行值
这是我的2D数组:
Array
(
[0] => Array
(
[id] => 9,5
[item] => Item A, Item B
)
[1] => Array
(
[id] => 3
[item] => Item C
)
)
在第一行中,ID
和item
有逗号分隔的值。我想在新数组中将数据提取到单个值中,以便输出是这样的:
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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
输出:( demo )
Output: (Demo)
下面的代码应完成工作。但是我不明白为什么您首先没有单独创建这些项目。
输出:( demo )
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.
Output: (Demo)
要将原始行值定为就地,然后随后遇到了界定值到数组的末尾,请使用
foreach()
并通过引用修改行以避免需要跟踪其索引。以下片段实际上将进行3次外循环的迭代,因为在循环完成之前将添加第一行的去溶解值作为新的第三行。当没有发现逗号时,简短的爆炸过程可以改善片段的性能。
代码:( demo )
输出:
在遇到的逗号降低的值(不将它们附加到将它们附加到将它们附加到逗号)上结束),我可能会使用
array_reduce()
构建结果数组。 ( demo )输出:
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)
Output:
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)Output: