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 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥15 DruidDataSource一直closing
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了
  • ¥50 STM32单片机传感器读取错误
  • ¥50 power BI 从Mysql服务器导入数据,但连接进去后显示表无数据
  • ¥15 (关键词-阻抗匹配,HFSS,RFID标签)
  • ¥50 sft下载大文阻塞卡死
  • ¥15 机器人轨迹规划相关问题