如何在PHP中将数组推入数组中的数组

时间:2013-08-12 13:22:10

标签: php arrays json

大家好我有以下代码:

$shops = array();
foreach($json as $var)
{
    if (in_array($var['shop'], $shops)) {}
    else
    {
        array_push($shops,$var['shop']);
        array_push($shops->$var['shop'],array('revenue' => 0, 'numberofbooks' => 0));
    }
}

我想要以下内容:

Shops
  => shop1
    => revenue
    => numberofbooks
  =>shop2
    => revenue
    => numberofbooks

但插入第三个数组不起作用,任何人都可以帮助我吗?

2 个答案:

答案 0 :(得分:1)

试试这个:

$shops = array();

foreach($json as $var){
    if (!isset($shops[$var['shop']])){ // use ! as "not", and use isset()
        $shops[$var['shop']] = array('revenue' => 0, 'numberofbooks' => 0);
    }
}

PHP的in_array()检查数组中是否存在值,而不是存在键。

答案 1 :(得分:-1)

试试这个(未经测试)

$shop = array();
foreach($json as $var)
{
    if(!in_array($var['shop'], $shop)){
        $shops[$var['shop']] = array('revenue' => 0, 'numberofbooks' => 0);
    }
}