问题描述
我在另一篇文章中发现了这段代码,我发现它很有帮助,但对我来说这只是等式的一半.根据以下代码,我需要从数据库中取出字符串,将其分解为二维数组,编辑数组中的值并将其分解为相同格式的存储.所以特别是按照与现有脚本相同的顺序向后.
来自其他帖子的代码>>
$data = 我喜欢搞笑电影\n 我喜欢stackoverflow dot com \n 我喜欢摇滚歌曲";$data =explode("\n", $data);$out = array();$步= 0;$last = count($data);$last--;foreach($data as $key=>$item){foreach(explode(' ',$item) 作为 $value){$out[$key][$step++] = $value;}如果($key!=$last){$out[$key][$step++] = ' ';//不插入最后一个空格"}}打印 '';print_r($out);打印 '</pre>';
引用的代码插入单独的数组元素,这些元素只有一个空格作为值.人们可能想知道这些带来了什么好处.
您可以使用以下两个功能:
函数explode2D($row_delim, $col_delim, $str) {return array_map(function ($line) use ($col_delim) {返回爆炸($col_delim,$line);},explode($row_delim, $str));}函数 implode2D($row_delim, $col_delim, $arr) {返回内爆($row_delim,array_map(函数($row)使用($col_delim){返回内爆($col_delim,$row);}, $arr));}
它们彼此相反,与标准的 explode 和 implode 函数非常相似,不同之处在于您需要指定两个分隔符:一个分隔行,另一个另一个用于列.
以下是您将如何使用它:
$data = "我喜欢搞笑电影\n 我喜欢stackoverflow dot com \n 我喜欢摇滚歌曲";$arr =explode2D(" \n ", " ", $data);//操作数据//...$arr[0][2] = "吓人";$arr[2][2] = "balad";//转换回来$str = implode2D(" \n ", " ", $arr);
查看它在 repl.it 上运行.
I found this code in another post which I found quite helpful but for me it's only half the equation. In line with the following code, I need to take the string from a database, explode it into the 2d array, edit values in the array and implode it back ready for storage in the same format. So specifically backwards in the same order as the existing script.
The code from the other post >>
$data = "i love funny movies \n i love stackoverflow dot com \n i like rock song";
$data = explode(" \n ", $data);
$out = array();
$step = 0;
$last = count($data);
$last--;
foreach($data as $key=>$item){
foreach(explode(' ',$item) as $value){
$out[$key][$step++] = $value;
}
if ($key!=$last){
$out[$key][$step++] = ' '; // not inserting last "space"
}
}
print '<pre>';
print_r($out);
print '</pre>';
The quoted code inserts separate array elements which just have a space as value. One can wonder what benefit those bring.
Here are two functions you could use:
function explode2D($row_delim, $col_delim, $str) {
return array_map(function ($line) use ($col_delim) {
return explode($col_delim, $line);
}, explode($row_delim, $str));
}
function implode2D($row_delim, $col_delim, $arr) {
return implode($row_delim,
array_map(function ($row) use ($col_delim) {
return implode($col_delim, $row);
}, $arr));
}
They are each other's opposite, and work much like the standard explode and implode functions, except that you need to specify two delimiters: one to delimit the rows, and another for the columns.
Here is how you would use it:
$data = "i love funny movies \n i love stackoverflow dot com \n i like rock song";
$arr = explode2D(" \n ", " ", $data);
// manipulate data
// ...
$arr[0][2] = "scary";
$arr[2][2] = "balad";
// convert back
$str = implode2D(" \n ", " ", $arr);
See it run on repl.it.
这篇关于分解并将其分配给多维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!