将php中的数组拆分为键和值

时间:2014-01-31 09:34:17

标签: php arrays

我有格式的数组

数组([0] => A = 1 [1] => B = 2 [2] => C = 3 [3] =>)

如何生成显示值为

的表格

A B C

1 2 3

其中A,B,C是键,1,2,3是值?

编辑。

下面的代码是“非法偏移类型”错误

$responses = Array ( [0] => A=1 [1] => B=2 [2] => C=3 [3] => );

foreach ($responses as $response) {
    $key = split("=", $response[0]);
    $value= split("=", $response[1]);

        if($key != "" && $value != "") {
        $data[$key] = $value;    // <<<<< "Illegal offset type" error on this line
    }
}
?>
<!-- displaying the results of the query -->
<table>
    <?php foreach ($data as $key => $value): ?>
    <tr><td><?php echo $key; ?></td><td><?php echo $value; ?></td></tr>
    <?php endforeach; ?>
</table>

7 个答案:

答案 0 :(得分:1)

您可以将键和数组从值拆分为单独的数组,如下所示

<?php
$responses = array('A=1', 'B=2', 'C=3');
foreach ($responses as $value) {
    $split = explode('=', $value);
    $array1[$split[0]] = $split[1];
}
print_r($array1);
?>

输出:http://codepad.org/QdIsKIja

答案 1 :(得分:1)

这有效

$o = Array('a'=>1,'b'=>2);
$keys = array_keys($o);
$val = array_values($o);

答案 2 :(得分:0)

这样做

<?php
$arr=array (  "A=1" , "B=2" ,"C=3"  );

foreach($arr as $v){

    $str=explode('=',$v);
    $arr1[$str[0]]=$str[1];


}

print_r($arr1);

<强>输出

Array
(
    [A] => 1
    [B] => 2
    [C] => 3
)

答案 3 :(得分:0)

因此,您希望显示数组的每个值,然后显示每个键。好消息,你可以通过foreach循环轻松完成。

$array = array("A", "B", "C");
echo "<p><strong>";              
foreach( $array as $key => $value )
{
    echo $key, " ";
}
echo "</p></strong>";
echo "<p>";
foreach( $array as $key => $value )
{
    echo $value, " ";
}
echo "</p>";    

答案 4 :(得分:0)

<?php
$a=array("A=1","B=2","C=3");
foreach($a as $val)
{
 $split=explode("=",$val); 
 $b[$split[0]]=$split[1];
}
echo "<pre>";
print_r($b);
echo "</pre>";
?>

答案 5 :(得分:0)

你可以试试这个。

<table>
   <tr>
      <?
        foreach($arr as $item => $value){
            $values=explode("=",$value);
      ?>
            <td><?= $values[0]; ?></td>
      <? } ?>
   </tr>
   <tr>
       <?
        foreach($arr as $item => $value){
            $values=explode("=",$value);
      ?>
            <td><?= $values[1]; ?></td>
      <? } ?>

   </tr>
</table>

答案 6 :(得分:0)

$newArray=array("A"=>1,"B"=>2,"C"=>3);

foreach($newArray as $key=>$val)
{
  echo $key."=>".$val."<br>";
}