php将键/值插入关联数组


php insert key/value into associative array

我正在尝试将几个新的Key/Value对插入到特定位置的关联数组中。从我对SO的其他阅读中,我确信我必须循环遍历数组,并在设置条件时插入新值。

这是当前阵列

array(
    (int) 0 => array(
        'Product' => array(
            'id' => '59',
            'title' => ' Blue Dress',
            'Review' => array(
                'id' => '7',
                'product_id' => '59',
                'Review' => array(
                    (int) 0 => array(
                        'average' => '3.0000'
                    )
                )
            )
        )
    )
    (int) 1 => array(
        'Product' => array(
            'id' => '60',
            'title' => 'Red Dress',
            'Review' => array()
        )
    )
)

密钥审查并不总是有数据,但当它有数据时,我想插入一个新的密钥值,类似于以下摘录

    (int) 0 => array(
        'Product' => array(
            'id' => '59',
            'title' => ' Blue Dress',
            'Review' => array(
                'id' => '7',
                'product_id' => '59',
                'Review' => array(
                    (int) 0 => array(
                        'average' => '3.0000'
                        'some_value' => '5'
                    )
                )
            )
        )
    )

我试过几次都没成功。非常感谢您的帮助。

您可以这样做:

if(!empty($your_array[index]['Product']['Review'])){
  $your_array[index]['Product']['Review']['Review'][index]['some_value'] = 'new_value';
}

在您的示例中,它可能是:

if(!empty($your_array[0]['Product']['Review'])){
  $your_array[0]['Product']['Review']['Review'][0]['some_value'] = 'new_value';
}

再说一遍,你没有提到你的代码。所以,很难弄清楚你到底想要什么!

您应该遍历您的数组并将当前值传递为reference:

// Notice & sign before variable
foreach ($data as &$product)
{
    if ($product['Product']['Review'])
    {
        // or iterate through Review array
        $product['Product']['Review']['Review'][0]['some_value'] = 5;
    }
}