我有一个这样的字符串:
2,100|7,104|15,1110
我如何转换它以便在每个|
之前获得第一个值的数组?
Array
(
[2] => 100
[7] => 104
[15] => 1100
)
答案 0 :(得分:2)
这是一种做法
$str = '2,100|7,104|15,1110';
$arr1 = explode("|",$str);
if(sizeof($arr1) > 0 ){
$final_array = array() ;
foreach($arr1 as $data){
$arr2 = explode(",",$data);
$final_array[$arr2[0]] = $arr2[1];
}
}
print_r($final_array);
答案 1 :(得分:1)
您可以使用array_walk和explode来执行此操作。
$array = array();
$string = "2,100|7,104|15,1110";
array_walk(explode("|", $string), function($value) use(&$array) {
$group = explode(",", $value);
$array[$group[0]] = $group[1];
});
PHP 5.4 +
答案 2 :(得分:0)
使用explode
<?php
$pipeString = "2,100|7,104|15,1110";
$exploded = explode("|", $pipeString);
$outputArray = array();
for($i = 0, $l = count($exploded); $i < $l; $i++){
$keyValues = explode(",", $exploded[$i]);
$outputArray[$keyValues[0]] = $keyValues[1];
}
var_dump($outputArray);
?>
答案 3 :(得分:0)
你在问题上有一个错字,所以我做一个假设。你可以这样做。
$str = "2,100|7,104|15,1100";
foreach (explode("|", $str) as $part) {
$parts = explode(",", $part);
$my_array[$parts[0]] = $parts[1];
}
答案 4 :(得分:0)
像Yatin Trivedi所说,爆炸两次应该会给你你想要的结果:
$string = '2,100|7,104|15,1110';
$result = array();
foreach (explode('|', $string) as $entry) {
$values = explode(',', $entry);
$result[$values[0]] = $values[1];
}
答案 5 :(得分:0)
<?php
function explodeThem($string) {
$explode0= explode("|", $string);
for ($i=0; $i<count($explode0); $i++) {
$explode1 = explode(",", $explode0[$i]);
$newArray[$explode1[0]] = $explode1[1];
}
return $newArray;
}
$string = "2,100|7,104|15,1110";
echo "<pre>";
var_dump(explodeThem($string));
echo "</ pre>";