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);
?>
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"));
Related
I am having trouble getting the name of a dynamic key from a JSON string.
I am using PHP
This is a sample of the JSON
{
"_text": "this is a test",
"entities": {
"dynamic_key": [
{
"confidence": 0.99,
"value": "thi is the answer"
}
]
},
"msg_id": "1234532123"
}
I am using foreach to go trough the json key and get the values
foreach ($json as $obj) {
$search_term = $obj->_text;
$msg_id = $obj->msg_id;
}
But I am not sure how to get the value of the "dynamic_key" which changes every time, and because of that I also cannot get the values of "confidence and value" keys.
Any ideas on how to approach this?
Followed #Dimi, solution. This is what I ended up with
$data=json_decode($json,true);
foreach ($data['entities'] as $key=>$val)
{
echo "Entity: $key";
foreach ($data['entities'] as $keys){
$conf = $keys[0]['confidence'];
$answer = $keys[0]['value'];
echo "conf: $conf, answ: $answer";
}
}
Can you provide a couple more examples?
Or try this code and let us know if it breaks
<?php
$json='{
"_text": "this is a test",
"entities": {
"dynamic_key": [
{
"confidence": 0.99,
"value": "thi is the answer"
}
]
},
"msg_id": "1234532123"
}';
$data=json_decode($json,true);
foreach ($data['entities'] as $key=>$val)
{
echo "VALUE IS $key\n values are ";
var_dump($val);
}
Using the data you've shown, there doesn't seem to be an array for the starting JSON.
But with that data the following will use foreach to both fetch the key and the data and then another sub-loop to fetch the confidencevalue...
$search_term = $json->_text;
$msg_id = $json->msg_id;
foreach ( $json->entities as $key => $entities ) {
echo $key.PHP_EOL;
foreach ( $entities as $entity) {
echo $entity->confidence.PHP_EOL;
}
}
If you decode the JSON as an array and if the dynamic key is the only key under entities, then:
$array = json_decode($json, true);
$dynamic = current($array['entities']);
$confidence = $dynamic['confidence'];
$value = $dynamic['value'];
Or shorter:
$confidence = current($array['entities'])['confidence'];
You can probably use reset, current and maybe array_pop etc.
I have a JSON file like this
[
{
"item_id": "342",
"item_title": "James"
},
{
"item_id": "374",
"item_title": "Fred"
}
]
And I would like to get the item_title in PHP but using the item_id.
How would I go about this?
I have
$item_id = 374;
$url = 'file.json';
$data = file_get_contents($url);
$items = json_decode($data);
Thank you.
You can use array_search() and array_column() if you know that key will always exist
echo $items[array_search($item_id,array_column($items,'item_id'))]['item_title'];
https://3v4l.org/Qddcj
Otherwise go for functional approach
$items = json_decode($data,true);
function getItemTitle($array,$item_id){
$key = array_search($item_id,array_column($array,'item_id'));
if($key !==false && isset($array[$key]['item_title'])){
return $array[$key]['item_title'];
}else{
return "no title found for given id ".$item_id;
}
}
echo getItemTitle($items,$item_id);
Output:- https://3v4l.org/ikKWY
In case if same id can be repeated multiple time
$items = json_decode($json,true);
foreach($items as $value){
if($value['item_id']==$item_id){
echo $value['item_title'].PHP_EOL;
}
}
Output:- https://3v4l.org/7oPHk
Some explanation: you should use foreach loop with if condition
Here is the sample code
<?php
$json='[
{
"item_id": "342",
"item_title": "James"
},
{
"item_id": "374",
"item_title": "Fred"
}
]';
$item_id = 374;
$items = json_decode($json);
//print_r($items);
foreach($items as $value){
if($value->item_id==$item_id){
echo $value->item_title;
}
}
You can check the desired output here
I have a json file with the following syntax:
[
{
"fields": {
"service_number": "service_number",
"physical_address": "physical_address",
"account_id": "account_id",
"contact_id": "contact_id"
},
"someId": "asd23f",
"status": "Active",
"perCode": "1",
"idCode": "0987",
"nextCode": "09"
},
{
"fields": {
"service_number": "service_number",
"physical_address": "physical_address",
"account_id": "account_id",
"contact_id": "contact_id"
},
"someId": "789096",
"status": "Active",
"perCode": "1",
"idCode": "076543",
"nextCode": "09"
}
]
I would like to use a for loop in order to add something like a userID before or after the nextCode. Is there any solution to this?
So far, I tried this:
$data = json_decode($file, true);
foreach ($data as $key => $val)
{
foreach ($val as $key=>$c)
{
if (is_array($c))
continue;
$data .= $data . "user_id:$userId";
}
}
Of course it does not make the trick, any ideas please?
There are a few problems.
First, the foreach loop works with a copy of the array it's iterating, so modifying one of the items there won't change the original array.
Then, your inner foreach loop is overwriting the $key from the outer loop. That would cause problems, but it's okay, because you don't actually need the inner loop.
Finally, after you've decoded the JSON string, $data will be an array, so appending to it with .= won't work, and even if it did, you'd just be sticking something on the end of it rather than at the specific point where your loop is.
Just refer to the specific key you need and set the value there.
$data = json_decode($file, true);
foreach ($data as $key => $val)
{
$data[$key]['user_id'] = $userId;
}
$data = json_encode($data);
Another way which is slightly shorter is pass the value by reference &:
$data = json_decode($file, true);
foreach ($data as &$val) {
$val['user_id'] = $userId;
}
https://3v4l.org/ZF4Ve
This is how you can add an element to a parsed JSON and recostruct it back into a JSON:
// parse the JSON into an array
$data = json_decode($file, true);
foreach ($data as $key => $val)
{
// add the userID to each element of the main array
// it will be inserted after the last element (after nextCode)
$data[$key]['userID'] = 'some-id';
}
// if needed, parse the array back to JSON
$data = json_encode($data);
I explain to you
The following expression converts the information from string to array
$data = json_decode ($file, true);
So in your foreach you only have to add the key
$data = json_decode($file, true);
foreach ($data as $key => $val)
{
foreach ($val as $k=>$c)
{
if (is_array($c))
continue;
$data[$k]['user_id'] = $userId;
}
}
I see everybody answered for array options. I don't see why not using object, though.
I would do it like this:
$data = json_decode($file);
foreach ($data as &$field)
{
$field->userID = $userId;
}
$data = json_encode($data);
i have a json array
[
{
"id":1.25,
"name":"rose",
"Number":15,
"SSN":[
12345,
3455
]
},
{
"id":1.15,
"name":"orchid",
"Number":7,
"SSN":[
12345,
3455
]
}
]
i want to get the id value if user searched with any ssn or name or by number.the input for search may not be single value that means it may be combination of ssn and name or it may be name,ssn and number .Any combination of name number ,ssn may be inputs .i have to get id value if the inputs matches using php .i used xpath for xml but i want to search fron json.can someone suggest me with any idea..thank you...
To search user ID by analyzing JSON string use the following approach with array_filter and array_intersect_assoc functions:
$json_str = '[ { "id":1.25, "name":"rose", "Number":15, "SSN":[ 12345, 3455 ] }, { "id":1.15, "name":"orchid", "Number":7, "SSN":[ 12345, 3455 ] }]';
$decoded = json_decode($json_str, true);
// base search structure
$search_structure = ['name' => "", 'Number' => 0];
// let's say, the following inputs have come from API (some of them may be empty or omitted)
$number = 7;
$ssn = "3455";
if ($number && is_numeric($number)) $search_structure['Number'] = $number;
$search_structure = array_filter($search_structure); // filtering out empty params
$count_params = count($search_structure);
$user_id = 0;
foreach ($decoded as $item) {
if ($count_params == count(array_intersect_assoc($search_structure, $item))) {
if (!$ssn || ($ssn && in_array($ssn, $item['SSN']))) {
$user_id = $item['id'];
break;
}
}
}
print_r(($user_id)? "User id: $user_id" : "User with specified params not found!");
The output:
User id: 1.15
Lets $json contains an array string
$ar = json_decode($json, true);
$id = false;
foreach ($ar as $i)
if ($i["name"] == "rose" and $i["Number"] == 15)
{ $id = $i["id"]; break; }
if ($id !== false) {
// use $id
}
Preferably, convert the json data to native PHP Object and then using foreach, loop over the object and extracting the ID of the Objects that match the given SSN Number. The result of the extraction would be assigned to an array. Below is a Commented procedure of 1 possible way of going about this:
<?php
// WE ASSUME, JUST FOR TESTING PURPOSES THAT THE SSN NUMBER WE ARE LOOKING FOR IS 4567
$ssnNumber = 4567; //3455;
// CREATE A NEW ARRAY VARIABLE TO HOLD THE IDs YOU DESIRE & INITIALIZE IT TO AN EMPTY ARRAY
$arrIDS = array();
$jsonData = '[
{
"id" :1.25,
"name" :"rose",
"Number" :15,
"SSN" :[
12345,
3455
]
},
{
"id" :1.15,
"name" :"orchid",
"Number" :7,
"SSN" :[
12345,
3455
]
},
{
"id" :1.75,
"name" :"orchid",
"Number" :79,
"SSN" :[
4567,
89012
]
}
]';
// CONVERT $jsonData TO NATIVE PHP OBJECT
$objJson = json_decode($jsonData);
// LOOP THROUGH THE PHP OBJECT & TEST IF A GIVEN SSN EXIST.
foreach($objJson as $key=>$data){
// CHECK IF THE $data->SSN IS SET:
if(isset($data->SSN) && is_array($data->SSN)){
// CHECK IF THE SSN ARRAY CONTAINS THE GIVEN SSN NUMBER.
if(in_array($ssnNumber, $data->SSN)){
$arrIDS[] = $data->id;
}
}
}
var_dump($arrIDS); // DISPLAY: array (size=1) 0 => float 1.75
Alternatively, one could as well encapsulate the above Routine withina Function for re-usability like so:
<?php
function getIDBySSN($jsonData, $ssnNumber){
$arrIDs = array();
$objJson = json_decode($jsonData);
// LOOP THROUGH THE PHP OBJECT & TEST IF A GIVEN SSN EXIST.
foreach($objJson as $key=>$data){
// CHECK IF THE $data->SSN IS SET:
if(isset($data->SSN) && is_array($data->SSN)){
// CHECK IF THE SSN ARRAY CONTAINS THE GIVEN SSN NUMBER.
if(in_array($ssnNumber, $data->SSN)){
$arrIDs[] = $data->id;
}
}
}
return $arrIDs;
}
var_dump(getIDBySSN($jsonData, $ssnNumber)); // PRODUCES THE SAME RESULT
Test it HERE:
I have a json file with data like this (this is a partial view of the file to show structure):
{
"state": {
"ALABAMA": {
"ZOLD": [ "101", "102" ],
"ZNEW": [ "11", "12" ]
},
"ALASKA": {
"ZOLD": [ "5001", "5002", "5003", "5004", "5005", "5006", "5007", "5008", "5009", "5010"],
"ZNEW": [ "21", "22", "23", "24", "25", "26", "27", "28", "29", "20"]
}
}
}
What I want to do is search through it to find a value in the ZOLD field = $OLD, then return the value of the corresponding ZNEW array. I've tried going in with foreach and can get the arrays to echo out, but I'm not sure of what the value will be. Here's the code I have:
function translateZone($OLD)
{
$OLD = "5010"; //for testing purposes a constant but will be variable
$zStr = file_get_contents('getnew.json');
$zJson = json_decode($zStr,true);
foreach($zJson as $key=> $jsons)
{
foreach($jsons as $key=>$values)
{
foreach($values as $key=>$vals)
{
$counter=0;
foreach($vals as $key=>$vls)
{
$counter ++;
echo var_dump($vls);//I can see the values,but now what?
if ($vls == $OLD)
{
$zTemp = Help here -some array value of counter??
}
}
}
return $zTemp;
}
}
I've searched through a bunch of other questions but haven't found something close enough to help with the problem.
Additional information: I may or may not know the "state" string (i.e. "Alaska") but I may want to return this information as well based on the found value.
Thanks for the help.
Instead of trying to loop through ZOLD, you could use array_search (assuming that the $OLD value can only appear once in the data). This function will either return a number for the index of the value you search for or false if it cannot find it:
$index = array_search($OLD,$values['ZOLD']);
if ($index !== FALSE) {
$zTemp = $values['ZNEW'][$index];
}
This would replace your two innermost for loop (as you need the other loops to get down to this level) and iterate through each state. At this point as well, $key would be defined to your state name.
Here is another way to complete your task, this one with array_map function:
$jsonArray = json_decode($your_file_content, true);
$oldVal = "5005";
$result = [];
foreach( $jsonArray["state"] as $k => $v ) {
/**
* Here we're building an array or pairs ZOLD => ZNEW values
*/
$pairs = array_map(function($o, $n) {
return [ $o => $n ];
}, $v["ZOLD"], $v["ZNEW"]);
/**
* Filling up the result
*/
foreach( $pairs as $p )
if( isset($p[$oldVal]) )
$result[] = [
"state" => $k,
"ZNEW" => $p[$oldVal]
];
}
var_dump($result);
$result dump will contains a list or assoc arrays with "state" and "ZNEW" keys, if the corresponding ZNEW values will be found