使用键PHP将字符串转换为数组
问题描述:
I am trying to take an array with delimited strings and turn it into a multi dimensional array with named keys. Its easy to do it with numbers for keys but in my case I want to assign a key to each. The keys are slug, title, and type which correspond to keys 0,1,2 in each array.
array(
'thisslug|This title|text',
'thatslug|Thats title|text',
'anotherslug|Another title|dropdown',
);
I want to end up with
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')
),
我试图将带有分隔字符串的数组转换为带有命名键的多维数组。 它很容易用键的数字来做,但在我的情况下,我想为每个键分配一个键。 键是slug,title和type,对应于每个数组中的键0,1,2。 p>
array(
'hisslug | this title | text',\ n'thatslug |那就是标题|文字',
'anotherslug |另一个标题|下拉列表',
);
code> pre>
我想最终用 p>
array(
array('slug'=>'thisslug','title'=>'this title','type'=>'text'),
array('slug'=>'thisslug','title'=>'此标题','type'=>'text'),
array('slug'=>'thisslug', 'title'=>'此标题','type'=>'text')
),
code> pre>
div>
答
$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]);
}
Or use array_combine
:
$keys = array('slug', 'title', 'type');
foreach ($array as $string) {
$row = explode('|', $string); // Explode the string
$result[] = array_combine($keys, $row);
}
答
do a for
loop on your current array and explode
the content .
$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];
}