字符串数组到数组的数组

时间:2012-03-18 02:47:46

标签: php arrays string 2d

我在PHP中有一个字符串数组,如下所示:

people = array("John","Kim");

我想将每个字符串转换为数组本身。基本上,我现在想要一个像

这样的二维数组
people(John[],Kim[]);

我一直在努力实施,我不知道该怎么做。

2 个答案:

答案 0 :(得分:1)

$people = array_fill_keys(array("John","Kim"), array());

答案 1 :(得分:0)

根据你的评论,你应该使用键或值的组合,如果你想用多维数组(我不确定是最好的方法,但不能说没有进一步的上下文) )。

$people = array(
   "john" => array()
   );

然后,当您想要添加产品时,请执行以下操作:

$people["john"]["couch"] = 3; // bought 3 times.
$people["john"][$item] = 0; // if you don't know the count yet for whatever reason.  You can always chagne it later the same way.

现在:

 foreach( $people as $person => $purchases ){
    echo UCFirst( $person );
    if( ! empty( $purchases ) ){
       echo ' has bought:<br />';
       foreach( $purchases as $item => $qty ){
          echo $item.' ('.$qty.')<br />';
       }
    }
 }

如果您打算使用named,我建议您始终将密钥设置为大写或小写。你的电话。

如果你给我们更多的代码/上下文,可能有更好的方法来做这些事情。