dongwusang0314 2014-07-06 02:50
浏览 16
已采纳

使用键PHP将字符串转换为数组

I am trying to take an array with delimited strings and turn it into a multi dimensional array with named keys. Its easy to do it with numbers for keys but in my case I want to assign a key to each. The keys are slug, title, and type which correspond to keys 0,1,2 in each array.

    array(
        'thisslug|This title|text',
        'thatslug|Thats title|text',
        'anotherslug|Another title|dropdown',
    );

I want to end up with

array(
   array('slug' => 'thisslug', 'title' => 'this title', 'type' => 'text'),
   array('slug' => 'thisslug', 'title' => 'this title', 'type' => 'text'),
   array('slug' => 'thisslug', 'title' => 'this title', 'type' => 'text')
),
  • 写回答

2条回答 默认 最新

  • doumi7854 2014-07-06 02:55
    关注
    $result = array();
    foreach ($array as $string) {
        $row = explode('|', $string); // Explode the string
        // Convert it to associative
        $result[] = array('slug' => $row[0], 'title' => $row[1], 'type' => $row[2]);
    }
    

    Or use array_combine:

    $keys = array('slug', 'title', 'type');
    foreach ($array as $string) {
        $row = explode('|', $string); // Explode the string 
        $result[] = array_combine($keys, $row);
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥60 ESP32怎么烧录自启动程序
  • ¥50 html2canvas超出滚动条不显示
  • ¥15 MATLAB四叉树处理长方形tif文件
  • ¥15 java业务性能问题求解(sql,业务设计相关)
  • ¥15 52810 尾椎c三个a 写蓝牙地址
  • ¥15 elmos524.33 eeprom的读写问题
  • ¥15 使用Java milo连接Kepserver服务端报错?
  • ¥15 用ADS设计一款的射频功率放大器
  • ¥15 怎么求交点连线的理论解?
  • ¥20 软件开发方法学习来了