I want to retrieve a single value from this php array. My array in PHP is:
Array
(
[0] => stdClass Object
(
[id] => 27
[id_customer] => 19
[my_cart] => Array
(
[c81e728d9d4c2f636f067f89cc14862c] => Array
(
[id] => 2
[qty] => 1
[price] => 39000
[name] => HEBERGEMENT WEB MUTUALISE PREMIUM
[rowid] => c81e728d9d4c2f636f067f89cc14862c
[subtotal] => 39000
)
[a87ff679a2f3e71d9181a67b7542122c] => Array
(
[id] => 4
[qty] => 1
[price] => 150000
[name] => HEBERGEMENT WEB MUTUALISE ULTIMATE
[rowid] => a87ff679a2f3e71d9181a67b7542122c
[subtotal] => 150000
)
)
1
[created_at] => 2020-03-30
)
)
The problem is that I can not get qty, name, price
I tried by doing this in my foreach
foreach($cart_data as $cd){
echo 'ID Table: '.$cd->id.'<br>';
echo 'ID customer: '.$cd->id_customer.'<br>';
$data = $cd->my_cart;
if(is_array($data)){
foreach($data as $s){
echo 'My cart: '.$s;
}
}
}
But nothing is happened! I want to get price, name and qty.
To get several keys from my_cart
array, try to write the loop like this :
foreach($cart_data as $cd){
echo 'ID Table: '.$cd->id.'<br>';
echo 'ID customer: '.$cd->id_customer.'<br>';
$data = $cd->my_cart;
if(is_array($data)){
$filtered = [];
$keys = ['qty', 'name', 'price']; // the keys
$column_keys = array_flip($keys); // getting keys as values
foreach ($data as $key => $val) {
// getting only those key value pairs, which matches $column_keys
$item = array_intersect_key($val, $column_keys);
if (!empty($item))
$filtered[$key] = $item;
}
echo 'My cart: <br/>';
print_r($filtered);
}
}
In this line:
echo 'My cart: '.$s;
The variable $s
holds an array, not a string. If you follow your data structure, the contents of $s
would be similar to this:
Array (
[id] => 4
[qty] => 1
[price] => 150000
[name] => HEBERGEMENT WEB MUTUALISE ULTIMATE
[rowid] => a87ff679a2f3e71d9181a67b7542122c
[subtotal] => 150000
)
So, in order to get name, qty, price, you'd need to change your inner loop to something like this:
foreach ($data as $s) {
echo 'Product name: ' . $s['name'] . '<br>';
echo 'Quantity: ' . $s['qty'] . '<br>';
echo 'Price: ' . $s['price'] . '<br>';
}
What happens when you try to use an array as a string is that it shows up as the string "Array" and will trigger a PHP Notice: Array to string conversion in [location]
. I'm guessing this error might be the reason you get nothing, instead of My cart: Array
.
I found the solution. When inserting into database I encode it like this htmlspecialchars(json_encode($data))
and decode in with json_decode
while getting the $data. So now I have this:
foreach($cart_data as $cd){
echo 'ID Table: '.$cd->id.'<br>';
echo 'ID customer: '.$cd->id_customer.'<br>';
$data = json_decode($cd->my_cart);
foreach($data as $row){
echo $row->name;
echo $row->qty;
echo $row->price;
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.