doutiaoku4495 2016-05-04 10:01
浏览 80
已采纳

转换为关联数组PHP

If you have this data:

1=Books
1.1=Action & Adventure
1.2=Arts, Film & Photography
1.2.1=Architecture
1.2.2=Cinema & Broadcast
1.2.3=Dance

The number on the data is the index. How can you put it in associative array? I want to know an example of associative array with that data. Thanks

  • 写回答

2条回答 默认 最新

  • duanbin4847 2016-05-04 10:06
    关注

    Can be done with explode() and foreach

    Steps:

    1) First explode the string with new line character .

    2) Loo over it.

    3) You will get individual row, explode() it with =.

    4) You will get required key in 0 and value in 1.

    5) Store it in array as key value pair. Done

    $str = '1=Books
    1.1=Action & Adventure
    1.2=Arts, Film & Photography
    1.2.1=Architecture
    1.2.2=Cinema & Broadcast
    1.2.3=Dance';
    $arr = explode("
    ", $str);
    $assoc = array();
    if (! empty($arr)) {
     foreach ($arr as $k => $v) {
      $temp = explode('=', $v);
      $assoc[$temp[0]] = $temp[1];
     }
    }
    echo '<pre>';print_r($assoc);echo '</pre>';
    

    Output:

    Array
    (
     [1] => Books
     [1.1] => Action & Adventure
     [1.2] => Arts, Film & Photography
     [1.2.1] => Architecture
     [1.2.2] => Cinema & Broadcast
     [1.2.3] => Dance
    )
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥15 stable diffusion
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿