php array implode

2019-08-29 17:25发布

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.

4条回答
老娘就宠你
2楼-- · 2019-08-29 17:45

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

查看更多
我命由我不由天
3楼-- · 2019-08-29 17:48

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);
查看更多
Summer. ? 凉城
4楼-- · 2019-08-29 17:53

One possibility would be like this

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

echo implode('|', array_map('mapKeyVal', 
                            array_keys($arry), 
                            array_values($arry)
                           )
      );
查看更多
三岁会撩人
5楼-- · 2019-08-29 18:01

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);
查看更多
登录 后发表回答