Implode data from a multi-dimensional array

前端 未结 7 860
梦毁少年i
梦毁少年i 2020-11-22 12:30

I\'m a novice at PHP and I need a quick solution to the following problem but can\'t seem to come up with one:

I have a multi-dimensional array like so



        
相关标签:
7条回答
  • 2020-11-22 12:34

    Although this question is related to string conversion, I stumbled upon this while wanting an easy way to write arrays to my log files. If you just want the info, and don't care about the exact cleanliness of a string you might consider:

    json_encode($array)
    
    0 讨论(0)
  • 2020-11-22 12:34

    In this situation implode($array,','); will works, becasue you want the values only. In PHP 5.6 working for me.

    If you want to implode the keys and the values in one like :
    blogTags_id: 1
    tag_name: google

    $toImplode=array();
    foreach($array as $key => $value) {
    $toImplode[]= "$key: $value".'<br>';
    }
    $imploded=implode('',$toImplode);
    

    Sorry, I understand wrong, becasue the title "Implode data from a multi-dimensional array". Well, my answer still answer it somehow, may help someone, so will not delete it.

    0 讨论(0)
  • 2020-11-22 12:38
    join(',', array_map(function (array $tag) { return $tag['tag_name']; }, $array))
    
    0 讨论(0)
  • 2020-11-22 12:40

    Quite simple:

    $input = array(
      array(
        'tag_name' => 'google'
      ),
      array(
        'tag_name' => 'technology'
      )
    );
    
    echo implode(', ', array_map(function ($entry) {
      return $entry['tag_name'];
    }, $input));
    

    http://3v4l.org/ltBZ0


    and new in php v5.5.0, array_column:

    echo implode(', ', array_column($input, 'tag_name'));
    
    0 讨论(0)
  • 2020-11-22 12:43

    array_map is a call back function, where you can play with the passed array. this should work.

    $str = implode(',', array_map(function($el){ return $el['tag_id']; }, $arr));
    
    0 讨论(0)
  • 2020-11-22 12:57

    very simple go for this

    $str;
    foreach ($arrays as $arr) {
    $str .= $arr["tag_name"] . ",";
    }
    $str = trim($str, ',');//removes the final comma 
    
    0 讨论(0)
提交回复
热议问题