我使用PHP,我有以下数组:
Array
(
[0] => 5 star
[1] => 65%
[2] => 4 star
[3] => 19%
[4] => 3 star
[5] => 9%
[6] => 2 star
[7] => 3%
[8] => 1 star
[9] => 4%
[10] => See all 931 reviews
)
我想构建一个数组如下:
Array
(
[5star] => 65%
[4star] => 19%
[3star] => 9%
[2star] => 3%
[1star] => 4%
[reviews] => 931
)
最后一个键值对的一部分需要一些字符串操作,是否有更高效/优雅的方法来实现上述结果而不是创建两个单独的数组然后将它们的值推送到第三个?
答案 0 :(得分:1)
试试这个
$newArray = array();
for($i=0;$i <= count($yourArrayname);$i++))
{
$key = $yourArrayname[$i];
$i++;
$value = $yourArrayname[$i];
$newArray[$key] = $value;
}
答案 1 :(得分:1)
只能建议ol&#39;普通while
:
$r = [];
$c = count($source);
$i = 0;
while ($i < $c - 1) {
$r[$source[$i]] = $source[$i + 1];
$i += 2;
}
$r[] = preg_replace('/[^\d]/', '', $source[$i]); // add the last 'nnn reviews' bit