按字符串名称构建数组或按字符串值创建多个数组
Build array by string name OR make multiple array by string values
我想通过打破主数组来构建一个数组或多个数组,我的数组就像,
Array
(
[0] => string1
[1] => 1
[2] => 2
[3] => 3
[4] => 66
[5] => 34
[6] => string1
[7] => aww
[8] => brr
[9] => string3
[10] => xas
)
所以基本上根据值 'string1' 我想创建一个 新数组或第一个数组 其中有 只有这三个值(1,2,3)和string2和string3相同,所以每个数组都有它的价值观(三)。
请帮我建立这个。
注意:所有字符串名称都是静态的。
提前谢谢你。
我喜欢的结果:
string1 array:
<pre>Array
(
[1] => 1
[2] => 2
[3] => 3
[4] => 66
[5] => 34
)
string2 array:
<pre>Array
(
[1] => aww
[2] => brr
)
string3 array:
<pre>Array
(
[1] => xas
)
我想这会让你得到你想要的。
It does assume that the first entry in the old array will be a keyword!
$old = array('string1',1,2,3,66,34,'string2','aww','brr','string3','xas');
$new = array();
$keywords = array('string1', 'string2', 'string3');
$last_keyword = '';
foreach ($old as $o) {
if ( in_array($o, $keywords) ) {
$last_keyword = $o;
} else {
$new[$last_keyword][] = $o;
}
}
print_r($new);
它会像这样创建一个新数组
Array
(
[string1] => Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 66
[4] => 34
)
[string2] => Array
(
[0] => aww
[1] => brr
)
[string3] => Array
(
[0] => xas
)
)
However I still maintain that it would be better to go back to where the original array gets created and look to amend that process rather than write a fixup for it
我想通过打破主数组来构建一个数组或多个数组,我的数组就像,
Array
(
[0] => string1
[1] => 1
[2] => 2
[3] => 3
[4] => 66
[5] => 34
[6] => string1
[7] => aww
[8] => brr
[9] => string3
[10] => xas
)
所以基本上根据值 'string1' 我想创建一个 新数组或第一个数组 其中有 只有这三个值(1,2,3)和string2和string3相同,所以每个数组都有它的价值观(三)。 请帮我建立这个。 注意:所有字符串名称都是静态的。
提前谢谢你。
我喜欢的结果:
string1 array:
<pre>Array
(
[1] => 1
[2] => 2
[3] => 3
[4] => 66
[5] => 34
)
string2 array:
<pre>Array
(
[1] => aww
[2] => brr
)
string3 array:
<pre>Array
(
[1] => xas
)
我想这会让你得到你想要的。
It does assume that the first entry in the old array will be a keyword!
$old = array('string1',1,2,3,66,34,'string2','aww','brr','string3','xas');
$new = array();
$keywords = array('string1', 'string2', 'string3');
$last_keyword = '';
foreach ($old as $o) {
if ( in_array($o, $keywords) ) {
$last_keyword = $o;
} else {
$new[$last_keyword][] = $o;
}
}
print_r($new);
它会像这样创建一个新数组
Array
(
[string1] => Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 66
[4] => 34
)
[string2] => Array
(
[0] => aww
[1] => brr
)
[string3] => Array
(
[0] => xas
)
)
However I still maintain that it would be better to go back to where the original array gets created and look to amend that process rather than write a fixup for it