php array implode

一世执手 提交于 2019-12-11 14:11:06

问题


I have this array:

array (size=5)
  35 => string '3' (length=1)
  24 => string '6' (length=1)
  72 => string '1' (length=1)
  16 => string '5' (length=1)
  81 => string '2' (length=1)

I want to implode id to get:

$str = '35-3|24-6|72-1|16-5|81-2';

How to get it the easy way?

Thanks.


回答1:


I haven't tested this, but it should be pretty straight forward ...

foreach($array as $key=>$item){
    $new_arr[] = $key."-".$item;
}

$str = implode('|', $new_arr);



回答2:


One possibility would be like this

function mapKeyVal($k, $v) {
    return $k . '-' . $v;
}

echo implode('|', array_map('mapKeyVal', 
                            array_keys($arry), 
                            array_values($arry)
                           )
      );



回答3:


You cannot can do this using implode, see @havelock's answer below, however it would be easier to use a loop or another form of iteration.

$str = "";

foreach ($array as $key => $value) {

    $str .= $key . "-" . $value . "|";

}

$str = substr(0, strlen($str)-1);



回答4:


Solution

You can do it cleanly by joining strings, while using eg. custom associative mapping function, which looks like that:

function array_map_associative($callback, $array){
    $result = array();
    foreach ($array as $key => $value){
        $result[] = call_user_func($callback, $key, $value);
    }
    return $result;
}

Full example and test

The full solution using it could look like that:

<?php

function array_map_associative($callback, $array){
    $result = array();
    foreach ($array as $key => $value){
        $result[] = call_user_func($callback, $key, $value);
    }
    return $result;
}

function callback($key, $value){
    return $key . '-' . $value;
}

$data = array(
    35 => '3',
    24 => '6',
    72 => '1',
    16 => '5',
    81 => '2',
);

$result = implode('|', array_map_associative('callback', $data));

var_dump($result);

and the result is:

string(24) "35-3|24-6|72-1|16-5|81-2"

which matches what you expected.

The proof is here: http://ideone.com/HPsVO6



来源:https://stackoverflow.com/questions/13331970/php-array-implode

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!