array_replace() / array_merge() | ( $_SESSION = array() ) argument is not an array?

怎甘沉沦 提交于 2019-12-04 14:11:15

array_replace returns the replaced array. So you need to do:

$base=array_replace($base, $replacement);

Also, I suggest using named keys consistently throughout, as opposed to mixing named and numeric:

$base = $_SESSION['cart'][$to_update]['quantity'];

EDIT:

This may not be exactly what you're going for...

I set up a test situation without using $_SESSION, and I got the same error you did. I changed the code as follows and no longer get the error.

$sesh=array(
    'cart'=>array(
        0=>array(
            'quantity'=>1
        )
    )
);

$to_update=0;
$new_quantity=5;

//$base = $sesh['cart'][$to_update]['quantity']; <--- changed this to line below
$base = $sesh['cart'][$to_update];

$replacement = $sesh['cart'][$to_update] = array('quantity' => $new_quantity);
$base=array_replace($base, $replacement);

echo"<pre>";print_r($base);echo"</pre>";

PHP FIDDLE: http://phpfiddle.org/main/code/mvr-shr

This have solved this issue:

Basically as per the structure: (Lets slice it into bits)

$_SESSION['cart'] = array();

then

$_SESSION['cart'][$name] = array('quantity' => 1);

finally:

$base = $_SESSION['cart'][$to_update]['quantity'] ;
$replacement = $_SESSION['cart'][$to_update] = array('quantity' => $_POST['option']);
array_replace($base, $replacement);

The reason why it says that the argument $base is not an array is because:

['quantity'] in $base is not an array as it forms the 'quantity' => 1 what we need is the array() value from the array('quantity' => 1); for it to be identified as an array.

So final answer should be: $base = $_SESSION['cart'][$to_update]; as there is only one array() recorded in where the $to_update resides so the replacement argument shall replace this identified array.

$_SESSION only exists when a Session starts. In order to do that you need to add on top of all your code session_start() otherwise the session will not start, unless you define it on php directives.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!