我有一个1d数组如下:
$arr = [
'itemName0' => "first Item",
'itemDesc0' => "first item's description",
'itemName1' => "second item",
'itemDesc1' => "third item's description",
];
我希望将其转换为2d数组,如下所示
$arr = [
0 => [
'itemName' => "first Item",
'itemDesc' => "first item's description",
],
1 => [
'itemName' => "second item",
'itemDesc' => "Second item's description",
],
];
实际上我有来自api响应的数据,其中包含除项目之外的其他细节..... {index} e.g。
$arr = [
'status' => 'success',
'blahblah' => 'this is just a test',
'itemName0' => "first Item",
'itemDesc0' => "first item's description",
'itemName1' => "second item",
'itemDesc1' => "third item's description",
];
但我只需要项目数据。
我试图使用array_map来获取项目,但不能..
array_map(function($value, $key){ strpos($key, 'item') === false ? false : $value; }, $arr));
我还在尝试.. anyideas会非常有帮助
答案 0 :(得分:2)
你可以试试这个 -
$arr = [
'itemName0' => "first Item",
'itemDesc0' => "first item's description",
'itemName1' => "second item",
'itemName2' => "second item's description",
];
$new = [];
foreach($arr as $key => $value) {
$index = sscanf($key, '%[A-Za-z]%d');
if(strpos($key, 'item') === 0) {
$new[$index[1]][$index[0]] = $value;
}
}
<强>输出强>
array(3) {
[0]=>
array(2) {
["itemName"]=>
string(10) "first Item"
["itemDesc"]=>
string(24) "first item's description"
}
[1]=>
array(1) {
["itemName"]=>
string(11) "second item"
}
[2]=>
array(1) {
["itemName"]=>
string(25) "second item's description"
}
}
答案 1 :(得分:0)
$arr = [
'itemName0' => "first Item",
'itemDesc0' => "first item's description",
'itemName1' => "second item",
'itemName2' => "third item's description",
'testKey1' => "Should be ignored",
'itemData' => "No numeric, so should also be ignored"
];
$newArray = [];
foreach($arr as $key => $value) {
list($keyName, $keyNumber) = sscanf($key, 'item%[A-Za-z]%d');
if (!is_null($keyNumber)) {
$newArray[$keyNumber]['item'.$keyName] = $value;
}
}
var_dump($newArray);
答案 2 :(得分:0)
我能做的最简单的是,
>> possibleValues = {'s', 'm', 'l', 'xl', 'xxl'};
>> data = {'s', 'm', 'xl', 'l', 'm', 'l', 'aaa'};
>> [~, result] = ismember(data, possibleValues)
result =
1 2 4 3 2 3 0
答案 3 :(得分:0)
首先,创建一个空的多维数组:
$multi_arr = array();
然后,遍历原始数组,
foreach($arr as $key => $val) { <br/>
//get last character from key<br/>
$k = substr($key, -1);<br/>
//get key index value from original key by removing last character<br/>
$index = rtrim($key, $k);<br/>
//Push values to multi dimensional array<br/>
$multi_arr[$k][$index] = $val;<br/>
}
答案 4 :(得分:0)
使用数组块方法是最简单的
$input_array = array('a', 'b', 'c', 'd', 'e','f');
print_r(array_chunk($input_array, 2));
输出:
Array
(
[0] => Array
(
[0] => a
[1] => b
)
[1] => Array
(
[0] => c
[1] => d
)
[2] => Array
(
[0] => e
[1] => f
)
)