I am trying to remove the key value from one associative array using PHP but it could not working as expected. I am explaining my code below.
<?php
$resultArr=array(array("stars"=>"3","starcount"=>3),array("stars"=>"4","starcount"=>4),array("stars"=>"5","starcount"=>5));
foreach ($resultArr as $key => $value) {
if (array_key_exists("stars", $value)) {
unset($value['stars']);
}
}
echo json_encode($resultArr);
?>
Here I need to remove all stars
key and its value from json array but my code is not working as expected.
Try this
$resultArr=array(array("stars"=>"3","starcount"=>3),array("stars"=>"4","starcount"=>4),array("stars"=>"5","starcount"=>5));
foreach ($resultArr as $key => $value) {
if (array_key_exists("stars", $value)) {
unset($resultArr[$key]['stars']);
}
}
echo json_encode($resultArr);
Explaination
You should unset key from $resultArr array by using $key
To separate Key and Value:
foreach ($resultArr as $key => $value) {
echo $key;
echo $value
}
Foreach statement copies value and it means $value variable has a copy of element instead original element. You can use access by key to direct access to element of array, for example:
foreach ($resultArr as $key => $value) {
if (array_key_exists("stars", $value)) {
unset($resultArr[$key]['stars']);
}
}
Also, you can use references
foreach ($resultArr as $key => &$value) {
if (array_key_exists("stars", $value)) {
unset($value['stars']);
}
}
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.