简体   繁体   中英

Array to comma separated string?

My php code is

public function getAllAttributes()
    {
        $this->dao->select('b_title');
        $this->dao->from($this->getTable_buttonsAttr());
        $result = $this->dao->get();
        if( !$result ) {
            return array() ;
        }
        return $result->result();
    }

$details = Modelbuttons::newInstance()->getAllAttributes();
$string = implode(', ', $details);
var_dump ($string) ;  ?>

I get this an array that looks like this:

 array (size=6)
          0 => 
            array (size=1)
              'b_title' => string 'test 10' (length=12)
          1 => 
            array (size=1)
              'b_title' => string 'test 11' (length=12)
          2 => 
            array (size=1)
              'b_title' => string 'test 12' (length=13)
          3 => 
            array (size=1)
              'b_title' => string 'test 13' (length=8)
          4 => 
            array (size=1)
              'b_title' => string 'test 14' (length=14)
          5 => 
            array (size=1)
              'b_title' => string 'test 15' (length=32)

How can I transform this array to a string like this with PHP?

$out = '10, 11, 12, 13, 14,15';

You can try this code.

$array = [['b_title' => 'test 10'],['b_title' => 'test 11']];
foreach($array as $a) {
    $values[] = explode(' ', $a['b_title'])[1];
}
echo implode(', ', $values);

Basic Example:

<?php
// your array
$array = array(
        array('b_title'=>'test 10'),
        array('b_title'=>'test 11'),
        array('b_title'=>'test 12'),
        array('b_title'=>'test 13')
    );

$newArr = array();
foreach ($array as $key => $value) {
    $newVal = explode(" ", $value['b_title']);
    $newArr[] = $newVal[1];
}
echo implode(',', $newArr); // 10,11,12,13
?>

Explanation:

First of all use explode() for your string value which help you to Split a string as required:

$newVal = explode(" ", $value['b_title']);

Than you can store index 1 in an array as:

$newArr[] = $newVal[1]; // array(10,11,12,13)

In last, you just need to use implode() function which help you to get comma separated data.

echo implode(',', $newArr); // 10,11,12,13

An alternative way to do.

$details = Modelbuttons::newInstance()->getAllAttributes(); /*[['b_title' => 'test 10'],['b_title' => 'test 11']];*/
$token = "";
foreach($details as $row1){
 $token = $token.$row1['b_title'].", ";
}
echo rtrim(trim($token),",");

Output : test 10, test 11

Explanation

Through foreach, all array values are now comma separated.

As of now, output will be test 10, test 11, . So, remove extra comma which trail in the end through rtrim() .

// Construct a new array of the stripped numbers
$flattenedArray = array_map(function($item) {
    list(, $number) = explode(' ', $item['b_title']);

    return $number;
}, $yourArray);

// Concatenate the numbers into a string joined by ,
$out = implode(', ', $flattenedArray);

This gives the result you want. It could do with a few conditions in there though to check arrays are in the correct format before manipulation etc.

There are many ways to skin this cat -- Here's one:

<?php
$out = '';

foreach ($array as $arrayItem) {
    $out .= $arrayItem['b_title'] . ', ';
}

// Remove the extraneous ", " from the $out string.
$out = substr($out, 0, -2);
?>

Or if you were also wanting to remove the "test " portion of the 'b_title' key's value; then you could accomplish it like so:

<?php
$out = '';

foreach ($array as $arrayItem) {
    $out .= str_replace('test ', '', $arrayItem['b_title']) . ', ';

}

// Remove the extraneous ", " from the $out string.
$out = substr($out, 0, -2);
?>
$test_array = array(
  0 => array('b_title' => 'test 10'),
  1 => array('b_title' => 'test 11'),
  2 => array('b_title' => 'test 12'),
  3 => array('b_title' => 'test 13'),
  4 => array('b_title' => 'test 14'),
  5 => array('b_title' => 'test 15'),
);
$result = "";
$result1 = array_walk($test_array, function ($value, $key) use(&$result) {
    $result .= ",".array_pop(explode(" ", reset($value))).",";
    $result = trim($result, ",");
});

Output: $out = '10, 11, 12, 13, 14,15';

Explanation

Iterate over array by using PHP's native array_walk() which will reduce forloops and then prepare array by using explode(),array_pop() and trim() which is likely required to prepare your required string.

You can try this also

$check  = array(array ('b_title' => array('test 10'))
    ,array('b_title' => array('test 11'))
    ,array('b_title' => array('test 12'))
    ,array('b_title' => array('test 13'))
    ,array('b_title' => array('test 14'))
    ,array('b_title' => array('test 15')));

$srt = "";
foreach($check as $kye => $val)
{
    $title = $val['b_title'][0];
    $var = explode(' ',$title);
    $srt .= trim($var[1]).', ';
}
$srt = substr(trim($srt),0,-1);

You can use on mentioned URL solution Click here

foreach ($arr as $k=>$val) {
    $v = explode (' ', $val['b_title']);
    $out .= $v[1].',';
}
$out = rtrim ($out, ',');
echo '<pre>'; print_r($out); die;

Try this,

foreach($test_array as $val)
{
  $new_array[] = preg_replace('/\D/', '', $val['b_title']);
}

$out = implode(',', $new_array);
echo $out;

OUTPUT

10,11,12,13,14,15

DEMO

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM