我正在尝试将带有分隔字符串的数组转换为带有命名键的多维数组。它很容易用键的数字来做,但在我的情况下,我想为每个键分配一个键。键是slug,title和type,对应于每个数组中的键0,1,2。
array(
'thisslug|This title|text',
'thatslug|Thats title|text',
'anotherslug|Another title|dropdown',
);
我想以
结束array(
array('slug' => 'thisslug', 'title' => 'this title', 'type' => 'text'),
array('slug' => 'thisslug', 'title' => 'this title', 'type' => 'text'),
array('slug' => 'thisslug', 'title' => 'this title', 'type' => 'text')
),
答案 0 :(得分:3)
$result = array();
foreach ($array as $string) {
$row = explode('|', $string); // Explode the string
// Convert it to associative
$result[] = array('slug' => $row[0], 'title' => $row[1], 'type' => $row[2]);
}
或使用array_combine
:
$keys = array('slug', 'title', 'type');
foreach ($array as $string) {
$row = explode('|', $string); // Explode the string
$result[] = array_combine($keys, $row);
}
答案 1 :(得分:0)
在当前阵列上执行for
循环,并explode
内容。
$arr = array(
'thisslug|This title|text',
'thatslug|Thats title|text',
'anotherslug|Another title|dropdown',
);
$newArr = array();
for($i = 0; $i < count($arr); $i++) {
$strArr = explode('|', $arr[$i]);
$newArr['slugs'] = $strArr[0];
$newArr['title'] = $strArr[1];
$newArr['type'] = $strArr[2];
}