php array implode

2019-08-29 17:17发布

问题:

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