假设我有一个逗号分隔的字符串,如下所示:
array
(
[1] => Sunday,
[2] => Monday,
[3] => Tuesday,
[4] => Wednesday,
[5] => Thursday,
[6] => Friday,
[7] => Saturday,
);
如何在PHP中使用成对数组,如下所示 -
yourArray.sort({$0.date.timeIntervalSinceNow < $1.date.timeIntervalSinceNow})
答案 0 :(得分:2)
简单回答(需要PHP&gt; = 5.5.0):如果您不需要在每个值的末尾使用尾随逗号
let lotoArray = lotoDictionary.allObjects as [Loto]
lotoArray.sort { $0.hafta < $1.hafta }
如果确实需要尾随逗号,可以添加:
$string = '1,Sunday,2,Monday,3,Tuesday,4,Wednesday,5,Thursday,6,Friday,7,Saturday';
$data = array_chunk(
explode(',', $string),
2
);
$newArray = array_combine(
array_column($data, 0),
array_column($data, 1)
);
var_dump($newArray);
答案 1 :(得分:1)
如果您有像工作日和工作日数字这样的静态数据,那么使用静态数组肯定是最简单的:
$weekdays = array(
1 => 'Sunday',
2 => 'Monday',
3 => 'Tuesday',
4 => 'Wednesday',
5 => 'Thursday',
6 => 'Friday',
7 => 'Saturday',
);
如果你有来解析逗号分隔的字符串,你可以使用它:
$string = '1,Sunday,2,Monday,3,Tuesday,4,Wednesday,5,Thursday,6,Friday,7,Saturday';
$parts = explode(',', $string);
$weekdays = array();
for ($i = 0; $i < count($parts); ) {
$weekdays[$parts[$i]] = $parts[++$i];
++$i;
}
print_r($weekdays);
输出:
Array
(
[1] => Sunday
[2] => Monday
[3] => Tuesday
[4] => Wednesday
[5] => Thursday
[6] => Friday
[7] => Saturday
)
它很漂亮,但它完成了工作:)。
答案 2 :(得分:0)
这将为你工作。
$string = '1,Sunday,2,Monday,3,Tuesday,4,Wednesday,5,Thursday,6,Friday,7,Saturday.';
$dtd = explode(',', $string);
$array = array();
$i = 1;
foreach ($dtd as $key => $value){
if($key % 2 == 1){
$array[$i++] = $value;
}
}
print_r($array);//Array ( [1] => Sunday [2] => Monday [3] => Tuesday [4] => Wednesday [5] => Thursday [6] => Friday [7] => Saturday. )