不使用implode()函数将数组转换为字符串

时间:2016-05-21 18:38:42

标签: php for-loop concatenation

假设我有一个如下所示的数组:

size

我想连接它,所以它采用这种格式并且是一个字符串:

Array
(
    [0] => Model Number
    [1] => 987
    [2] => Interface
    [3] => 987
    [4] => GPU
    [5] => 98
    [6] => Core Clock
    [7] => 79
    [8] => Boost Clock
    [9] => 87
    [10] => CUDA Cores
    [11] => 987
 )

implode函数并不适合这个,因为我需要在每两个索引之后Array { Model Number: 987; Interface: 987; GPU: 98; Core Clock: 79; ... And so on ... } 。 我所有使用循环的尝试都失败了。 (未定义的索引和内存不足错误)

提前感谢您的帮助!

4 个答案:

答案 0 :(得分:2)

这是一个简单的方法:

$string = "";

foreach(array_chunk($array, 2) as $value) {
    $string .= "{$value[0]}: {$value[1]};\n";
}

答案 1 :(得分:0)

这应该有效:

<强> PHP

$specs = [];
$count = count($array);
for ($i = 0; $i < $count $i+=2) {
    $specs[] = $array[$i] . ': ' . $array[$i + 1];
}

这将输出:

array(6) {
  [0]=>
  string(17) "Model Number: 987"
  [1]=>
  string(14) "Interface: 987"
  [2]=>
  string(7) "GPU: 98"
  [3]=>
  string(14) "Core Clock: 79"
  [4]=>
  string(15) "Boost Clock: 87"
  [5]=>
  string(15) "CUDA Cores: 987"
}

EvalIn

答案 2 :(得分:0)

假设这是你的数组

$array = array(
    'Model Number',
    987,
    'Interface',
    987,
    'GPU',
    98,
    'Core Cloc',
    79,
    'Boost Clock',
    87,
    'CUDA Cores',
    987
);

您可以遍历列表并创建一个新数组

$result = array();
foreach($array as $key => $value)
    if($key % 2 == 0) // Every two index
        $result[$key] = $value . ": ";
    else if(isset($result[$key-1]))
        $result[$key-1] .= $value;

结果将是

array(6) {
  [0]=>
  string(16) "Model Number:987"
  [2]=>
  string(13) "Interface:987"
  [4]=>
  string(6) "GPU:98"
  [6]=>
  string(12) "Core Cloc:79"
  [8]=>
  string(14) "Boost Clock:87"
  [10]=>
  string(14) "CUDA Cores:987"
}

答案 3 :(得分:0)

<?php

$array = Array
(
    0 => 'Model Number',
    1 => 987,
    2 => 'Interface',
    3 => 987,
    4 => 'GPU',
    5 => 98,
    6 => 'Core Clock',
    7 => 79,
    8 => 'Boost Clock',
    9 => 87,
    10 => 'CUDA Cores',
    11 => 987
 );

 $imploded = array_map(function ($a) {
   return implode($a, ': ');
 }, array_chunk($array, 2));


 print_r($imploded);