Reputation: 45
I can get data from a website with CURL and I can convert this data to json.
I want to remove an element from json.
Output:
{
"test":{
"numbers":
[
"1",
"27",
"32",
"1",
"94",
"1",
"8"
]
}
}
I want to remove "1" from my json. How can I do that? Thank you for your help.
my code:
<?php
function Curlconnect($start,$end,$website) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $website);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$website = curl_exec($ch);
preg_match_all('@'.$start.'(.*?)'.$end.'@si',$website,$ver);
return $ver[1];
curl_close($ch);
}
function nt($start,$bit,$data,$a) {
preg_match_all('@'.$start.'(.*?)'.$bit.'@si',$data,$ver);
return $ver[1];
}
$url = 'http://www.url.com';
$getdata = Curlconnect('<h4','h4>',$url);
$jsonData = ["data"];
$jsonData["numbers"] = [];
for ($a=0; $a<count($getdata); $a++) {
$printdata = nt('>','</',$getdata[$a],$a);
$jsonData["test"]["numbers"][] = $printdata[0];
}
echo json_encode($jsonData);
?>
Upvotes: 0
Views: 768
Reputation: 2877
You can use array_search()
to look for a value in an array (your $jsonData["test"]["numbers"]
array), and use unset()
to remove the value from the array.
Because there are multiple "1" values, and array_search()
only returns the first key found, you'll need to use a while loop to ensure you find all the values to remove.
function remove_value_from_array ($val, $array)
{
while ( ($key = array_search($array, $val)) !== false)
{
unset($array[$key]);
}
return $array;
}
$jsonData["test"]["numbers"] = remove_value_from_array($jsonData["test"]["numbers"], "1");
Edit: I've remembered a simpler way - and a way that allow you to search for multiple values. You can simply use array_diff()
to search for values, and remove them.
// Remove a single value of "1"
$jsonData["test"]["numbers"] = array_diff($jsonData["test"]["numbers"], array(1));
// Remove multiple values, of "1", "2", "5", and the word "test"
$jsonData["test"]["numbers"] = array_diff($jsonData["test"]["numbers"], array(1, 2, 5, "test"));
Upvotes: 1