i have the following array when i dd($test)
:
array:1 [
0 => {#81
+"1": "1"
+"2": "2"
}
]
and i want to remove the second field and value so the output will be
array:1 [
0 => {#81
+"1": "1"
}
]
ive been trying to use array_splice
and unset
but it doesnt get what i want to remove the field and value, am i doing something wrong? how do i make it happen? thanks in advance.
I'm not sure why unset is not working for you, but this code
<?php
$var = [
0 => [
"1" => "1",
"2" => "2",
]
];
var_dump($var);
unset($var[0]["2"]);
var_dump($var);
Will produce this output:
array(1) {
[0]=>
array(2) {
[1]=>
string(1) "1"
[2]=>
string(1) "2"
}
}
array(1) {
[0]=>
array(1) {
[1]=>
string(1) "1" /// leaving only the one you needed
}
}
You can check it here: https://3v4l.org/37X5s
i'm guessing the code you printed out here wasn't properly formatted but anyways, to remove and item key and value from an associative array on php, you use the php unset($var)
function. Take for instance $data = array("key1"=>"value1", "key2"=>"value2");
when i call unset($data["key2"]);
$data
now becomes contains only key 1 and value 1.
There's 2 approaches I've found to recreate this, and only one has worked when using unset
.
Approach 1 - Using (object)[];
$test = [
(object)[
"1" => "1",
"2" => "2"
];
Approach 2 - Using stdClass()
:
$array = new stdClass();
$array->{"1"} = "1";
$array->{"2"} = "2";
$test = [
$array
];
At this point, I try to unset()
the 2nd key of the first entry in $test
:
unset($test[0]->{"2"});
dd($test);
The output of dd($test);
following this unset()
is:
// Approach 1
array:1 [▼
0 => {#407 ▼
+"1": "1"
+"2": "2"
}
]
// Approach 2
array:1 [▼
0 => {#407 ▼
+"2": "2"
}
]
It seems that using unset()
works as expected when using stdClass()
, but if you're casting an array
as an object
like I tried in Approach 1, unset()
will look to work but not actually do anything.
The only way I could get Approach 1 to work is like so:
foreach($test AS $tKey => $array){
$array = (array)$array;
foreach($array AS $aKey => $value){
if($key == 2){
unset($array[$aKey]);
}
}
$test[$tKey] = (object)$array;
}
Which works, but seems inefficient as I'm casing the casted array to an array
then back to an object
. Hopefully this gives you some insight into the issue here.