PHP爆炸并将其分配给多维数组MKII :) [英] PHP explode and assign it to a multi-dimensional array MKII :)

查看:49
本文介绍了PHP爆炸并将其分配给多维数组MKII :)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在另一篇文章中找到了这段代码,发现对我很有帮助,但对我而言,它只是方程式的一半.内联以下代码,我需要从数据库中提取字符串,将其分解为2d数组,在数组中编辑值,然后将其内爆以相同格式存储.因此,具体来说,是按照与现有脚本相同的顺序向后退.

i found this code in another post which i found quite helpful but for me its only half the equation. inline 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.

你们中的任何巫师都可以帮助我吗?:)谢谢!

can any of you wizards help me out please? :) thank you!

另一篇文章中的代码>>

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

它们彼此相反,它们的工作原理与标准的 explode implode 功能相同,不同之处在于您需要指定两个定界符:一个定界符;以及另一列.

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.

这是您将如何使用它:

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

看到它在 repl.it 上运行.

这篇关于PHP爆炸并将其分配给多维数组MKII :)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆