如何从字符串创建多维数组 [英] How to create a multi-dimensional array from string
本文介绍了如何从字符串创建多维数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
试图从字符串创建多维数组。我的字符串是:
Looking to create a multi-dimensional array from a string. My string is:
13,4,3 | 65,1,1 | 27,3,2
13,4,3|65,1,1|27,3,2
我想将其存储在一个数组中,假设它看起来像这样:
I want to store it in an array which I'm assuming would look like this:
$multi_array = array
(
array(13,4,3),
array(65,1,1),
array(27,3,2)
);
所以我可以用$ multi_array [1] [1]调用它,它应该返回 4 。
So I can call it with $multi_array[1][1], which should return "4".
以下是我到目前为止的代码:
Here's the code I have so far:
$string = "13,4,3|65,1,1|27,3,2";
$explode = explode("|", $string);
$multi_array = array(); //declare array
$count = 0;
foreach ($explode as $value) {
$explode2 = explode(",", $value);
foreach ($explode2 as $value2) {
// I'm stuck here....don't know what to do.
}
$count++;
}
echo '<pre>', print_r($multi_array), '</pre>';
推荐答案
尝试这种方式,
$data = '13,4,3|65,1,1|27,3,2';
$return_2d_array = array_map (
function ($_) {return explode (',', $_);},
explode ('|', $data)
);
print '<pre>';
print_r ($return_2d_array);
print '</pre>';
OR 与您自己的代码
$string = "13,4,3|65,1,1|27,3,2";
$explode = explode("|", $string);
$multi_array = array(); //declare array
$count = 0;
foreach ($explode as $key=>$value) { // see changes on this line
$explode2 = explode(",", $value);
foreach ($explode2 as $value2) {
$multi_array[$key][$count] = $value2;
$count++; // see count variable position changes here
}
}
echo '<pre>', print_r($multi_array), '</pre>';
这篇关于如何从字符串创建多维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文