PHP中的数组到字符串转换的数组

时间:2015-05-26 10:08:58

标签: php multidimensional-array

如何转换此数组:

$data = Array
(
    [0] => Array
        (
            [0] => 125
            [pcode] => 125
        )

    [1] => Array
        (
            [0] => 275
            [pcode] => 275
        )

    [2] => Array
        (
            [0] => 600
            [pcode] => 600
        )

    [3] => Array
        (
            [0] => 675
            [pcode] => 675
        )

    [4] => Array
        (
            [0] => 1031
            [pcode] => 1031
        )

    [5] => Array
        (
            [0] => C335
            [pcode] => C335
        )

)

成这样的字符串:

  

$ new_string =" ' 125'' 275'' 600'' 675'' 1031'' C335& #39; &#34 ;;

3 个答案:

答案 0 :(得分:2)

非常简单:

$tmp=array();
foreach($data as &$element)
{
    $tmp[]='\''.addslashes(current($element)).'\'';
}

echo implode(',',$tmp);

您可以在http://sandbox.onlinephpfunctions.com/code/5c338914de2d627ff39ea7e7dab5a30e060c39f4

上试用

答案 1 :(得分:1)

下面的代码得到你的输出:

<?php
$data = Array
(
    1 => Array
        (
            0 => 125,
            'pcode' => 125
        ),

    2 => Array
        (
            0 => 275,
            'pcode' => 275
        ),
    3 => Array
    (
        0 => 675,
        'pcode' => 675
    ),
    4 => Array
    (
        0 => 675,
        'pcode' => 675
    ),
     5 => Array
    (
        0 => 1031,
        'pcode' => 1031
    )
    );




$i=0;
foreach($data as $k=>$val)
{

    if(is_array($val))
    {
        foreach($val as $k1=>$v1)
        {
            if(strcmp($k1,'pcode'))
            {
                if($i==0)
                {echo '"'."'".$v1."',";
                }
                else if($i+1==sizeof($data))
                {
                    echo "'".$v1."'".'"';
                }
                else
                {
                    echo "'".$v1."',";
                }

            }

        }
    }
    $i++;
}
?>

答案 2 :(得分:0)

$data=array( 
'1'=> array
    (
        '0' => 275,
        'pcode' => 275
    ),
'2' => array
    (
        '0' => 600,
        'pcode' => 600
    ),
'3' => array
    (
        '0' => 675,
        'pcode' => 675
    ),
'4' => array
    (
        '0' => 1031,
        'pcode' => 1031
    ),
'5' => array
    (
        '0' => 'C335',
        'pcode' => 'C335'
    )
    );

$val=implode(',',array_map("FunctionArr",$data));

function FunctionArr($value)
{
return $value[0];
} 
echo $val;

现在你可以根据需要获得字符串

作为var_dump($val)