Errors with json_decode, array and foreach - php

I use this code for Virtuemart:
$product_id_to_remove = 3;
$cart = json_decode($_SESSION['__vm']['vmcart']);
foreach($cart->cartProductsData as $k => $v){
if($v->virtuemart_product_id == $product_id_to_remove) unset($cart->cartProductsData[$k]);
}
$_SESSION['__vm']['vmcart'] = json_encode($cart);
but I get the fatal error: Cannot use object of type stdClass as array in ... line 4. If I add true at json_decode($_SESSION['__vm']['vmcart']) I get the warning: Invalid argument supplied for foreach().
How to resolve the problem?
p.s. I'm beginner in php and don't know json_ at all. The code is suggested by the link: stackoverflow.com/questions/28691203/how-to-remove-a-single-product-from-mod-virtuemart-cart

$cart->cartProductsData behaves like an array but it's actually an object
try this:
change
unset($cart->cartProductsData[$k])
to
unset($cart->cartProductsData->$k)

Related

Fatal error: Cannot use object of type stdClass as array in CodeIgniter

I'm getting the error "Fatal error: Cannot use object of type stdClass as array in" on line 37 which happens to be
public function getMatkul1(){
$matkul = $this->rest->get('ambilmk', 'json');
foreach ($matkul as $key => $value) {
if(($value['semester'] % 2 ) == $semester){
echo '<option value='.$value['kmk'].'>'.$value['mk'].'</option>';
}
}
}
Anyone know what's wrong with the above code? Or what this error means?
PHP shows this error when you are trying to use an PHP object as an array, i.e. using [] instead of -> .
Since, I don't know what elements are inside $matkul and how are they located, I can only guess that the problem arises due to using [] in $value. e.g. try replacing
$value['semester'] with $value->semester
And with kmk & mk too. It might work.
To debug yourself, have to use :
print_r($matkul) or print_r($value)
Then, in the printed result observe how the elements are in the $matlkul or in $value; whether as an object or as an array. If $value is happened to be an object, then you have to use -> for semester, kmk, mk; not [ ].

Invalid argument supplied for foreach() php warning

Iam newbie to php and codeigniter.
I have error in php,
A PHP Error was encountered
Severity: Warning
Message: Invalid argument supplied for foreach()
Filename: controllers/search.php
Line Number: 44
Line 44 is: foreach ( $data as $key => $value )
There is some syntax error here,
inside this if statement, if (!empty($user['search'])), $data is printed correctly,whereas in this if statement,if(!empty($data)), $data is not printed. Can anyone help me resolve this issue.
The problem is you don't have any value inside your looping variable( $data ).
You can print their values for check whether the variable contains values.
Replace :
$data = json_decode($user['search'])->result;
By :
$data = json_decode($user['search'], true);
json_decode works that way :
var_dump(json_decode($json)); // returns object(stdClass)
var_dump(json_decode($json, true)); returns array
Your $data was an object, while foreach strictly wants an array.

Looping through json_decode with foreach loop error

I keep running into the error Warning: Invalid argument supplied for foreach() and for the life of me I can't figure out why. Here is my relevant code:
$Ids = $_POST["param-0"];
$toReturn = array();
$decodedJson = json_decode($Ids,TRUE);
stripslashes($decodedJson);
foreach($decodedJson as $id)
{
... do stuff with $toReturn...
}
$Ids is a string from a previous file that is encoded with json_encode. I added the stripslashes because it was recommended in another question on Stack Overflow, but it didn't help. If I change the beginning of the foreach loop to beforeach($toReturn as $id) the error goes away. Thanks!
edit: in the previous file, $_POST["param-0"] is an integer array that I returned with json_encode. With the testing data I am working with right now, ["15","18"] is what is being passed.
First you need to decode the json (which you already did)
$decodedJson = json_decode($Ids, True);
Then to grab each value from the json and, for example, echo it. Do this:
foreach ($decodedJson as $key => $jsons) { // This will search in the 2 jsons
foreach($jsons as $key => $value) {
echo $value; // This will show jsut the value f each key like "var1" will print 9
// And then goes print 16,16,8 ...
}
}
From top to botton:
$Ids = $_POST["param-0"];
This will trigger a notice if input data does not have the exact format you expect. You should test whether the key exists, for instance with isset().
$toReturn = array();
$decodedJson = json_decode($Ids,TRUE);
This will return null if input data is not valid JSON. You should verify it with e.g. is_null().
stripslashes($decodedJson);
If input data was valid we'll first get a warning:
Warning: stripslashes() expects parameter 1 to be string, array given
Then, if our PHP version is very old we'll have our array cast to a string with the word Array in it, and if our PHP version is recent we'll get null. Whatever, our data is gone.
If input data wasn't valid, we'll get an empty string.
foreach($decodedJson as $id)
{
... do stuff with $toReturn...
}
Neither null or strings (empty or not) are iterable. There's no nothing to do here. Our data is gone forever :_(
It ended up I was incorrectly encoding what I wanted decoded. All is well again, thanks for everyone's help!

Can't get value from array

I'm trying to output the value of the email value of an array, but have problems doing so.
The array is based on json_decode()
This is the error I receive
Fatal error: Cannot use object of type stdClass as array in /home/.... line 57
JSON (value of: $this->bck_content)
{"email":"test#email.com","membership_id":"0","fname":"Kenneth","lname":"Poulsen","userlevel":"1","created":"2012-04-23 10:57:45","lastlogin":"2012-04-23 10:58:52","active":"y"}
My code
# Display requested user details
$details_array = json_decode($this->bck_content);
$value = $details_array['email'];
print $value;
You need to use the second argument to json_decode to force array structures on JS objects.
json_decode($this->bck_content, true);
This will make sure all JS objects in the json are decoded as associative arrays instead of PHP StdObjects.
Of course that is assuming you want to use array notation to access them. If you're fine with using object notation then you can just use:
$value = $details_array->email;
try this one
$value = $details_array->email;
or
json_decode($json, true);
or
$details_array = (array)json_decode($json);
what have you done wrong is writen in error description

Fatal error: Uncaught Error: Cannot use a scalar as an array warning

I have the following code:
$final = [1 => 2];
$id = 1;
$final[$id][0] = 3;
The code seems to work fine, but I get this warning:
Warning: Cannot use a scalar value as an array in line X (the
line with: $final[$id][0] = 3).
Can anyone tell me how to fix this?
You need to set$final[$id] to an array before adding elements to it. Intiialize it with either
$final[$id] = array();
$final[$id][0] = 3;
$final[$id]['link'] = "/".$row['permalink'];
$final[$id]['title'] = $row['title'];
or
$final[$id] = array(0 => 3);
$final[$id]['link'] = "/".$row['permalink'];
$final[$id]['title'] = $row['title'];
The reason is because somewhere you have first declared your variable with a normal integer or string and then later you are trying to turn it into an array.
The Other Issue I have seen on this is when nesting arrays this tends to throw the warning, consider the following:
$data = [
"rs" => null
]
this above will work absolutely fine when used like:
$data["rs"] = 5;
But the below will throw a warning ::
$data = [
"rs" => [
"rs1" => null;
]
]
..
$data[rs][rs1] = 2; // this will throw the warning unless assigned to an array
Also make sure that you don't declare it an array and then try to assign something else to the array like a string, float, integer. I had that problem. If you do some echos of output I was seeing what I wanted the first time, but not after another pass of the same code.

Categories