dongyan1936 2017-07-11 07:27
浏览 43
已采纳

PHP - 从字符串和值构建数组

How can I build an array from string and values ?

For exemple :

            string              |        value
                                |   
objectId                        |   19
location.street                 |   Rue des clochets
translations.fr.idTranslation   |   4

And the result must be :

[
    'objectId' => 19,
    'location' => [
        'street' => 'Rue des clochets'
    ],
    'translations' => [
        'fr' => [
            idTranslation => 4
        ],
    ]
]

Obiviously, if the key already exists, it is complete, not duplicate.

Like : translation.fr.country | France

The array will become :

[
    'object' => 19,
    'location' => [
        'street' => 'Rue des clochets'
    ],
    'translations' => [
        'fr' => [
            'idTranslation' => 4,
            'country'       => 'France'
        ],
    ]
]

I think, using explode is the good way but I don't find the good syntax.

The head of my method is :

 public function buildArray($key, $value) {

 }

I call this method in a foreach.

And the array is a property.

Thank's for help.

  • 写回答

2条回答 默认 最新

  • duansao20000508 2017-07-11 07:38
    关注
    public function buildArray($key, $value) {   
      $keys = explode('.', $key);
    
      $x = count($keys) - 1;
      $temp = array($keys[$x] => $value);
      for($i = $x-1; $i >= 0; $i--)
      {
        $temp = array($keys[$i] => $temp);
      }
      return $temp
    }
    

    Something like this should work. Please appologize if it does not run without some work of you, it is untested, but it seems to work https://3v4l.org/3HBAY. Of course this will give you one array per key/value pair. You will have to merge the returning array (array_merge_recursive) with your result in your foreach.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作