2012-11-04 213 views
0

請幫我將數組轉換爲字符串。array to string(php)

陣列是這樣的:

Array 
(
    [0] => Array 
     (
      [0] => Array 
       (
        [red] => 255 
        [green] => 255 
        [blue] => 255 
        [alpha] => 127 
       ) 

      [1] => Array 
       (
        [red] => 255 
        [green] => 255 
        [blue] => 255 
        [alpha] => 127 
       ) 
      ... 

     ) 

) 

我試圖用破滅功能,但沒有結果......

$string = implode(", ", $pxlCorArr); 

PS:對不起,我的英語我來自烏克蘭。

+2

你要輸出字符串是什麼樣子? –

+0

你肯定會得到_some result_,但它看起來像[你正在將2維數組轉換爲字符串](http://stackoverflow.com/search?q=%5Bphp%5D+implode+multi+dimensional)。正如蒂姆所問,產出應該是什麼樣子? –

+0

我想輸出紅色,綠色,藍色,阿爾法 –

回答

2

這將是另一種可能性,如一個 功能,其中傳遞您最初的陣列和函數返回你所需要的字符串:

function getRGBAlpha($pxlCorArr) { 

    $rgbVals = array(); 
    foreach($pxlCorArr as $subArr) { 
     if(is_array($subArr)) { 
      foreach($subArr as $colValues) { 
       $rgbVals[] = implode('.', $colValues); 
      } 
     } 
    } 

    return implode(',', $rgbVals); 
} 

,所以你可以做到以下幾點,什麼地方在你的代碼,讓你需要的輸出:

echo getRGBAlpha($pxlCorArr); 

應該輸出:

255.255.255.127,255.255.255.127 
+1

thx你這麼多! –

5

陣列:

$pxlCorArr = 
    array(
     array (
      array('red' => 255, 
       'green' => 255, 
       'blue' => 255, 
       'alpha' => 127 
      ), 

      array('red' => 255, 
       'green' => 255, 
       'blue' => 255, 
       'alpha' => 127 
      ) 
    ) 
); 

代碼:

$output = ''; 
foreach ($pxlCorArr as $subArray) { 
    if(is_array($subArray)) { 
     foreach ($subArray as $subArray2) { 
      if(is_array($subArray2)) { 
       $output .= implode ('.', $subArray); 
       $output .= ','; 
      } 
     } 
    } 
} 
$output = rtrim($output, ','); 

輸出:

255.255.255.127,255.255.255.127

+0

'implode()'會更便宜,而不是整個級聯和修整;-) – Havelock

+0

@Havelock你說得對,糾正了我的答案! =) – Tivie

+0

請告訴我,我需要插入輸入數組 –

1
Array 
(
    [0] => Array 
     (
      [0] => Array 
       (
        [red] => 255 
        [green] => 255 
        [blue] => 255 
        [alpha] => 127 
       ) 

      [1] => Array 
       (
        [red] => 255 
        [green] => 255 
        [blue] => 255 
        [alpha] => 127 
       ) 
      ... 

     ) 

) 


$string = ''; 
$array = $exists_array[0]; 
foreach ($array as $key => $value) { 
$string .= $key." : ".$value."\n"; 
} 
print $string; 
0

使用array_walk在lambda表達式:

$implodevals = create_function('&$val', '$val = implode(".", $val);'); 
    array_walk($array, $implodevals); 
    print rtrim(implode(", ", $array), ","); 

輸入數組:

$array = Array 
    (
     0 => Array 
      (
       "red" => 255, 
       "green" => 255, 
       "blue" => 255, 
       "alpha" => 127 
      ), 

     1 => Array 
      (
       "red" => 255, 
       "green" => 255, 
       "blue" => 255, 
       "alpha" => 127, 
      ) 



    );