一个简单的问题,我该如何转换此字符串:
"'One' => 1,'Two' => 2,'Three' => 3,'Four' => 4,"
到这样的数组:
array['One'] = 1;
array['Two'] = 2;
array['Three'] = 3;
array['Four'] = 4;
答案 0 :(得分:3)
使用正则表达式和array_combine
preg_match_all('/\'(\w+)\'\s*=>\s*(\d+)/', $str, $m);
print_r(array_combine($m[1], $m[2]));
答案 1 :(得分:2)
$string = "'One' => 1,'Two' => 2,'Three' => 3,'Four' => 4,";
$array = explode(',',$string);
foreach($array as $item){
$new_items = explode(' => ', $item);
$key = $new_items[0];
$value = $new_items[1];
$new_array[][$key] = $value;
}
var_dump($new_array);
答案 2 :(得分:2)
这是一个经过测试的解决方案:
$input = "'One' => 1,'Two' => 2,'Three' => 3,'Four' => 4,";
$gen = new ArrayGenerator($input);
$this->assertSame([
'One' => 1,
'Two' => 2,
'Three' => 3,
'Four' => 4,
], $gen->translate());
这里是完整的代码
use PHPUnit\Framework\TestCase;
class FooTest extends TestCase
{
public function testItems()
{
$input = "'One' => 1,'Two' => 2,'Three' => 3,'Four' => 4,";
$parser = new Parser($input);
$this->assertEquals([
"'One' => 1",
"'Two' => 2",
"'Three' => 3",
"'Four' => 4"
], $parser->items());
}
public function testKeyValue()
{
$input = "'One' => 1";
$parser = new KeyValue($input);
$this->assertEquals([
"'One'",
"1",
], $parser->items());
}
public function testKeyValueWithoutQuotas()
{
$input = "'One' => 1";
$parser = new KeyValue($input);
$this->assertEquals([
"One",
"1",
], $parser->itemsWithoutQuotas());
}
public function test()
{
$input = "'One' => 1,'Two' => 2,'Three' => 3,'Four' => 4,";
$gen = new ArrayGenerator($input);
$this->assertSame([
'One' => 1,
'Two' => 2,
'Three' => 3,
'Four' => 4,
], $gen->translate());
}
}
class ArrayGenerator
{
private $input;
public function __construct(string $input)
{
$this->input = $input;
}
public function translate()
{
$parser = new Parser($this->input);
$parsed = $parser->items();
$trans = [];
foreach ($parsed as $item) {
$pair = new KeyValue($item);
$trans[$pair->itemsWithoutQuotas()[0]] = (int) $pair->itemsWithoutQuotas()[1];
}
return $trans;
}
}
class KeyValue
{
private $input;
public function __construct(string $input)
{
$this->input = $input;
}
public function items()
{
$exploded = explode(' => ', $this->input);
return $exploded;
}
public function itemsWithoutQuotas()
{
$items = $this->items();
foreach ($items as $key => $item) {
$items[$key] = str_replace("'", "", $item);
}
return $items;
}
}
class Parser
{
private $input;
public function __construct(string $input)
{
$this->input = $input;
}
public function items()
{
$exploded = explode(',', $this->input);
$exploded = array_filter($exploded, function ($item) {
return $item != "";
});
return $exploded;
}
}
答案 3 :(得分:1)
您可以简单地使用php函数array_flip:
array_flip —将所有键及其关联值交换到 数组
碰撞警告:
如果值多次出现,则将最新的键用作其值 价值,其他所有东西都会丢失。
示例#2 array_flip()示例:碰撞
<?php
$input = array("a" => 1, "b" => 1, "c" => 2);
$flipped = array_flip($input);
print_r($flipped);
?>
上面的示例将输出:
Array
(
[1] => b
[2] => c
)