仅基于已知键创建多维数组

时间:2018-09-03 15:41:04

标签: php

我正在尝试使用仅允许使用键的字符串将其转换为多维数组。

给出字符串:

"type:blue, type:red, shift:second, shift:first, category:circle, system:unknown"

只有可能的键:

$possibleKeys = [ "category", "shift", "type" ];

创建数组:

$searchArray = array( "type"  => [ "blue", "red" ],
                      "shift" => [ "second", "first" ],
                      "category" => [ "circle" ]
                     );

因此system:unknown不会添加到$searchArray中,因为它不在$possibleKeys数组中。

这是我的代码:

$myString = "type:blue, type:red, shift:second, shift:first, category:circle, system:unknown";

$params = explode( ",", $myString );
$possibleKeys = [ "category", "shift", "type", "chances" ];

$nodes = [];
foreach ($params as $param) {
    $node = explode( ":", $param );

    if (array_key_exists( $node[ 0 ], $nodes ) && in_array( $node[ 0 ], $possibleKeys )) {
        array_push( $nodes[ $node[ 0 ] ], $node[ 1 ] );
    } else {
        $nodes[ $node[ 0 ] ] = $node[ 1 ];
    }
}

但是当我var_dump时,数组是垃圾,有些键有多余的空格。

array(4) {
  ["type"]=>
  string(9) "blue"
  [" type"]=>
  string(8) "red"
  [" shift"]=>
  string(5) "first"
  [" category"]=>
  string(3) "circle"
}

我在做什么错了?

4 个答案:

答案 0 :(得分:2)

首先使用允许的键构建关联数组。

分解字符串-首先用逗号定界符将explode插入数组以获取一对,然后分别对trimexplode进行配对。如果左侧是允许的键,则将右侧添加到关联数组元素。和往常一样,有多种方法可以做到这一点,但这就是我目前的咖啡因水平所要求的...

<?php
$dataString="type:blue, type:red, shift:second, shift:first, category:circle, system:unknown";

$desiredResult=array();
foreach(array("category", "shift", "type") as $desiredKey){
    $desiredResult[$desiredKey]=array();
}

$tmpArr=explode(",",$dataString);

foreach($tmpArr as $pair){
    $pair=trim($pair);
    $pairArr=explode(":",$pair);
    if(isset($desiredResult[$pairArr[0]])){
        $desiredResult[$pairArr[0]][]=$pairArr[1];
    }
}

print_r($desiredResult);

?>

给予

Array
(
    [category] => Array
        (
            [0] => circle
        )

    [shift] => Array
        (
            [0] => second
            [1] => first
        )

    [type] => Array
        (
            [0] => blue
            [1] => red
        )

)

答案 1 :(得分:2)

您可以使用正则表达式查找值并仅循环可能的键。
这意味着它仅进行三个迭代即可找到所有值并将它们放入数组中。
preg_match将在完整字符串中找到与该键相关的所有单词。

$myString = "type:blue, type:red, shift:second, shift:first, category:circle, system:unknown";
$possibleKeys = [ "category", "shift", "type" ];

foreach($possibleKeys as $key){
    preg_match_all("/" . $key . ":(.*?),/", $myString, $m);
    $new[$key] = $m[1]; // $m[1] will hold all the matching values to the key searched for
}
var_dump($new);

输出为:

array(3) {
  ["category"]=>
  array(1) {
    [0]=>
    string(6) "circle"
  }
  ["shift"]=>
  array(2) {
    [0]=>
    string(6) "second"
    [1]=>
    string(5) "first"
  }
  ["type"]=>
  array(2) {
    [0]=>
    string(4) "blue"
    [1]=>
    string(3) "red"
  }
}

https://3v4l.org/XAeRC

答案 2 :(得分:0)

因为您用“,”爆炸,所以请尝试用“,”(逗号空间)爆炸。

答案 3 :(得分:0)

您可以对代码进行细微调整,并避免使用诸如trim()array_key_exits()之类的一些额外方法

<?php
$myString = "type:blue, type:red, shift:second, shift:first, category:circle, system:unknown";

$params = explode( ", ", $myString ); // explode by comma & space with
$possibleKeys = [ "category", "shift", "type", "chances" ];
$ignore = ['system'];

$nodes = [];
foreach ($params as $param) {
    $node = explode( ":", $param );
    if (in_array( $node[0], $possibleKeys )) {
        $nodes[$node[0]][] = $node[1];
    } else {
        $nodes[$node[0]] = $node[1];
    }
}

foreach($ignore as $key) {
   unset($nodes[$key]);
}

print '<pre>';
print_r($nodes);
print '</pre>';
?>

演示: https://3v4l.org/Udav9