Php 从数组创建关联数组
我怎样才能转变Php 从数组创建关联数组,php,arrays,Php,Arrays,我怎样才能转变 Array1 ( [0] => Some Text [1] => Some Other Text (+£14.20) [2] => Text Text (+£26.88) [3] => Another One (+£68.04) ) 进入关联数组,如下所示: Array2 ( [Some Text] => 0 //0 since there is no (+£val) part [Some Other
Array1
(
[0] => Some Text
[1] => Some Other Text (+£14.20)
[2] => Text Text (+£26.88)
[3] => Another One (+£68.04)
)
进入关联数组,如下所示:
Array2
(
[Some Text] => 0 //0 since there is no (+£val) part
[Some Other Text] => 14.20
[Text Text] => Text Text 26.88
[Another One] => 68.04
)
像这样的方法应该会奏效:
$a2 = array();
foreach ($Array1 as $a1) {
if (strpos($a1, '(') > 0) {
$text = substr($a1, 0, strpos($a1, '('));
$value = substr($a1, strpos($a1, '(')+3, strpos($a1, ')')-1);
} else {
$text = $a1;
$value = 0;
}
$a2[$text] = $value;
}
print_r($a2);
编辑:
也可以使用“分解”方法执行此操作:
$a2 = array();
foreach ($Array1 as $a1) {
$a1explode = explode("(", $a1, 2);
$text = $a1explode[0];
if ($a1explode[1]) {
$value = substr($a1explode[1],3);
} else {
$value = 0;
}
$a2[$text] = $value;
}
print_r($a2);
像这样的方法应该会奏效:
$a2 = array();
foreach ($Array1 as $a1) {
if (strpos($a1, '(') > 0) {
$text = substr($a1, 0, strpos($a1, '('));
$value = substr($a1, strpos($a1, '(')+3, strpos($a1, ')')-1);
} else {
$text = $a1;
$value = 0;
}
$a2[$text] = $value;
}
print_r($a2);
编辑:
也可以使用“分解”方法执行此操作:
$a2 = array();
foreach ($Array1 as $a1) {
$a1explode = explode("(", $a1, 2);
$text = $a1explode[0];
if ($a1explode[1]) {
$value = substr($a1explode[1],3);
} else {
$value = 0;
}
$a2[$text] = $value;
}
print_r($a2);
到目前为止,您有什么,它是如何工作的?到目前为止,您有什么,它是如何工作的?正则表达式和explode是其他选项,这取决于数据的一致性。感谢它的关闭,但它在“某些文本(文本文本)(+£14.20)”((“(+”现在末尾只有一个圆括号)的情况下不起作用[text text]=>7.18)“正则表达式和explode是其他选项,这取决于数据的一致性。这要感谢它的关闭,但它在“某些文本(text-text)(+14.20)”的情况下不起作用”(“to”(+“现在末尾只有一个圆括号”[text text]=>7.18)”