【问题标题】:Add explode array as keys to new array将爆炸数组作为键添加到新数组
【发布时间】:2014-01-15 09:19:24
【问题描述】:
$input = "hello|world|look|at|this";
$explode = explode("|", $input);
$array = array("Title" => "Hello!", "content" => $explode);

这将输出:

array(2) {
  ["Title"]=>
  string(6) "Hello!"
  ["content"]=>
  array(5) {
    [0]=>
    string(5) "hello"
    [1]=>
    string(5) "world"
    [2]=>
    string(4) "look"
    [3]=>
    string(2) "at"
    [4]=>
    string(4) "this"
  }
}

但我希望它们成为具有 NULL 作为值的键,因为我在后面的步骤中添加值。

知道如何让explode() 函数作为键返回吗? 有没有可用的功能?

【问题讨论】:

标签: php php arrays explode


【解决方案1】:

array_fill_keys 可以根据数组填充键:

array_fill_keys ($explode, null);

【讨论】:

    【解决方案2】:

    在爆炸上使用foreach 循环来添加它们:

    foreach($explode as $key) {
        $array["content"][$key] = "NULL";
    }
    

    【讨论】:

      【解决方案3】:

      array_flip($explode) 怎么样?那应该给你这个

      array(2) {
       ["Title"]=>
       string(6) "Hello!"
         ["content"]=>
          array(5) {
            [hello]=> 1
      

      没有nullvalues,但至少你把钥匙弄对了

      【讨论】:

      • 值不会为空。但是,您可以在之后执行某些操作,例如 foreach($new_explode as &$val) { $val = null; } after。
      【解决方案4】:
      $input = "hello|world|look|at|this";
      $explode = explode('|', $input);
      $nulls = array();
      foreach($explode as $x){ $nulls[] = null; };
      $array = array("Title" => "Hello!", "content" => array_combine($explode, $nulls));
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-11-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-10-04
        • 1970-01-01
        相关资源
        最近更新 更多