如何在php中创建关联数组

时间:2018-03-13 05:40:42

标签: php arrays

我有一个类似

的数组
Array
(
    [0] => 2,2-0-tc
    [1] => 2-0
    [2] => 2-0-tc
    [3] => 3,3-0-sc-v6
    [4] => 3-0-sc-v6
    [5] => 3-0sc-v6
    [6] => 5-0-sc-v8
)

我想从数组中提取逗号分隔值,然后创建新数组,如

Array
(
    [2] => 2,2-0-tc
    [2-0-tc] => 2,2-0-tc
    [2-0] => 2-0
    [3] => 3,3-0-sc-v6
    [3-0-sc-v6] => 3,3-0-sc-v6
    [3-0sc-v6] => 3-0sc-v6
    [5-0-sc-v8] => 5-0-sc-v8
)

感谢addvance

2 个答案:

答案 0 :(得分:0)

爆炸并迭代每个以逗号分隔的值,并防止使用isset条件进行覆盖。

代码:demo:https://3v4l.org/9ArV7

$array = [
    "2,2-0-tc",
    "2-0",
    "2-0-tc",
    "3,3-0-sc-v6",
    "3-0-sc-v6",
    "3-0sc-v6",
    "5-0-sc-v8"
];

foreach ($array as $item) {
    $values = explode(",", $item);
    foreach ($values as $value) {
        if (!isset($result[$value])) {
             $result[$value] = $item;
        }
    }
}
var_export($result);

输出:

array (
  2 => '2,2-0-tc',
  '2-0-tc' => '2,2-0-tc',
  '2-0' => '2-0',
  3 => '3,3-0-sc-v6',
  '3-0-sc-v6' => '3,3-0-sc-v6',
  '3-0sc-v6' => '3-0sc-v6',
  '5-0-sc-v8' => '5-0-sc-v8',
)

答案 1 :(得分:-1)

展开逗号分隔值并将其分配给新数组。

$arr = array
(
    0 => '2,2-0-tc',
    1 => '2-0',
    2 => '2-0-tc',
    3 => '3,3-0-sc-v6',
    4 => '3-0-sc-v6',
    5 => '3-0sc-v6',
    6 => '5-0-sc-v8'
);

$newArr = [];
foreach($arr as $key=>$val){ 
    $temp = explode (',', $val);
    foreach($temp as $new){
        $newArr[$new] = $val;
    }
}
print_r($newArr);

Demo