How can I remove specify string words with php - php

How can I remove string . I want to find string that've 2018 then I want to delete string until ,
{"2018-1-8":0,"2018-1-9":0,"2018-1-10":0,"2019-1-1":0,"2019-1-15":0}
How can I display like this
{"2019-1-1":0,"2019-1-15":0}
Note I want to remove "2018-1-8":0,"2018-1-9":0,"2018-1-10":0,

This string is valid JSON which you can parse using json_decode(). You can then modify the data as you want:
// Your string
$json = '{"2018-1-8":0,"2018-1-9":0,"2018-1-10":0,"2019-1-1":0,"2019-1-15":0}';
// Get it as an array
$data = json_decode($json, true);
// Pass by reference
foreach ($data as $key => &$value) {
// Remove if key contains '2018'
if (strpos($key, '2018') !== false) {
unset($data[$key]);
}
}
// Return the updated JSON
echo json_encode($data);
// Output: {"2019-1-1":0,"2019-1-15":0}
Another solution using array_walk():
$data = json_decode($json, true);
array_walk($data, function ($v, $k) use (&$data) {
if (strpos($k, '2018') !== false) { unset($data[$k]); }
});
echo json_encode($data);
// Output: {"2019-1-1":0,"2019-1-15":0}
See also:
passing by reference
strpos()
unset()
json_encode()

Try this maybe :
// Your string
$string = "{\"2018-1-8\":0,\"2018-1-9\":0,\"2018-1-10\":0,\"2019-1-1\":0,\"2019-1-15\":0}";
// Transform it as array
$array = json_decode($string);
// Create a new array
$new_array = array();
// Now loop through your array
foreach ($array as $date => $value) {
// If the first 4 char of your $date is not 2018, then add it in new array
if (substr($date, 0, 4) !== "2018")
$new_array[$date] = $value;
}
// Now transform your new array in your desired output
$new_string = json_encode($new_array);
Output of var_dump($new_string); is {"2019-1-1":0,"2019-1-15":0}

Related

PHP/MYSQL Replace text of keys in array of dictionaries

I have a MYSQL query that fetches an array of dictionaries or results which are returned via JSON in an api. In some cases, I would like to change the name of the dictionary keys in the results array.
For example, in the following case:
$var = '[{"player":"Tiger Woods"},{"player":"Gary Player"}]';
I would like to change it to:
$var = '[{"golfer":"Tiger Woods"},{"golfer":"Gary Player"}]'
It is not practical in this case to change the mysql query so I'd just like to replace the word "player" with the word "golfer" for the keys without disturbing the values.
In the above example, I would not want to change Gary Player's name so just using str_replace does not seem like it would work.
Is there a way to change all of the keys from "player" to "golfer" without changing any of the values?
Here is the snippet you can use
$var = '[{"player":"Tiger Woods"},{"player":"Gary Player"}]';
// json decode the json string
$temp = json_decode($var, true);
$temp = array_map(function($item){
// combining key and values
return array_combine(['golfer'], $item);
}, $temp);
print_r($temp);
// or echo json_encode($temp);
Demo.
Some argue that foreach is fastest,
foreach($temp as $k => &$v){
$v = array_combine(['golfer'], $v);
}
print_r($temp);
Demo.
Little hardcoded if more than one keys in single array,
foreach ($temp as $k => &$v){
$v['golfer'] = $v['player'];
unset($v['player']);
}
print_r($temp);
Demo.
Using recursion
function custom($arr, $newKey, $oldKey)
{
// if the value is not an array, then you have reached the deepest
// point of the branch, so return the value
if (!is_array($arr)) {
return $arr;
}
$result = []; // empty array to hold copy of subject
foreach ($arr as $key => $value) {
// replace the key with the new key only if it is the old key
$key = ($key === $oldKey) ? $newKey : $key;
// add the value with the recursive call
$result[$key] = custom($value, $newKey, $oldKey);
}
return $result;
}
$var = '[{"player":"Tiger Woods"},{"player":"Gary Player"}]';
$temp = json_decode($var, true);
$temp = replaceKey($temp, 'golfer', 'player');
print_r($temp);
Demo & source.
Using json way,
function json_change_key($arr, $oldkey, $newkey) {
$json = str_replace('"'.$oldkey.'":', '"'.$newkey.'":', json_encode($arr));
return json_decode($json, true);
}
$temp = json_change_key($temp, 'player', 'golfer');
print_r($temp);
Demo
If you want multiple key replace, here is the trick,
$var = '[{"player":"Tiger Woods", "wins":"10","losses":"3"},{"player":"Gary Player","wins":"7", "losses":6}]';
$temp = json_decode($var, true);
function recursive_change_key($arr, $set)
{
if (is_array($arr) && is_array($set)) {
$newArr = [];
foreach ($arr as $k => $v) {
$key = array_key_exists($k, $set) ? $set[$k] : $k;
$newArr[$key] = is_array($v) ? recursive_change_key($v, $set) : $v;
}
return $newArr;
}
return $arr;
}
$set = [
"player" => "golfers",
"wins" => "victories",
"losses" => "defeats"
];
$temp = recursive_change_key($temp, $set);
print_r($temp);
Demo.
$a = '[{"player":"Tiger Woods"},{"player":"Gary Player"}]';
$array = json_decode($a, true);
foreach($array as $key=>$value){
if(array_keys($value)[0] === "player"){
$array[$key] = ["golfer" => array_values($value)[0]];
};
}
echo json_encode($array);
you can write the value of the key to a new key and then delete the old.
renaming a key called "a" to "b", while keeping the value.
var json = {
"a" : "one"
}
json["b"] = json["a"];
delete json["a"];
for your example, just use this with a loop.
source: https://sciter.com/forums/topic/how-to-rename-the-key-of-json/

Parse JSON data from multiple options

I'm trying to parse JSON data in the format [{code:SE rate:1.294},{code:UK rate:2.353}] from this page:
http://www.mycurrency.net/service/rates
I have implemented an IP reader that detects the users location in a 2 letter country code. I want to pluck the correct data from that link with 'code' and return the value 'rate'. I was thinking I might have to do a foreach loop to iterate through all the countries?
This is my code, I hope this is what are you looking for.
First I create a new array $output to make it more easy to search
$string = file_get_contents("http://www.mycurrency.net/service/rates");
$json = json_decode($string, true);
foreach ($json as $key => $data) {
$output[$key]['code'] = $data['code'];
$output[$key]['rate'] = $data['rate'];
}
After that we use a function to search value in array and returning the key. I got it from here
function searchForRate($countryCode, $array) {
foreach ($array as $key => $val) {
if ($val['code'] === $countryCode) {
return $key;
}
}
return null;
}
and then I run the function with the first parameter as country code to get the keys of specific country code.
$find = searchForRate("BT", $output);
And then echo the rates from our $output array by key in $find variable
echo 'RATE = '.$output[$find]['rate'];
This is the complete codes
<?php
$string = file_get_contents("http://www.mycurrency.net/service/rates");
$json = json_decode($string, true);
foreach ($json as $key => $data) {
$output[$key]['code'] = $data['code'];
$output[$key]['rate'] = $data['rate'];
}
function searchForRate($countryCode, $array) {
foreach ($array as $key => $val) {
if ($val['code'] === $countryCode) {
return $key;
}
}
return null;
}
$find = searchForRate("BT", $output);
echo 'RATE = '.$output[$find]['rate'];
Example output:
RATE = 64.13

How to remove an object from JSON array in PHP

I have a JSON array. I want to delete the entry that have number 4 and return the left over array
$filters = '{"1":1,"2":2,"3":4}';
$fobj = json_decode($filters, TRUE);
foreach($fobj as $key => $value)
{
if (in_array(4, $fobj)) {
unset($fobj[4]);
}
}
echo $filters = json_encode($fobj );
But this echo does not give me what I want. I want it to return something like this:
{"1":1,"2":2}
You're removing the fourth value of the array, not the value. Use array_search instead
$filters = '{"1":1,"2":2,"3":4}';
$fobj = json_decode($filters, TRUE);
$search = array_search(4, $fobj);
if($search !== false) unset($fobj[$search]);
echo $filters = json_encode($fobj );
$index = array_search("4", $array);
unset($array[$index]);
http://php.net/manual/de/function.array-search.php
http://php.net/manual/de/function.unset.php
That's all. Hope it helps!

PHP renaming string if string already exists

I am storing some data in an array and I want to add the key to it if the title already exists in the array. But for some reason it's not adding the key to the title.
Here's my loop:
$data = [];
foreach ($urls as $key => $url) {
$local = [];
$html = file_get_contents($url);
$crawler = new Crawler($html);
$headers = $crawler->filter('h1.title');
$title = $headers->text();
$lowertitle = strtolower($title);
if (in_array($lowertitle, $local)) {
$lowertitle = $lowertitle.$key;
}
$local = [
'title' => $lowertitle,
];
$data[] = $local;
}
echo "<pre>";
var_dump($data);
echo "</pre>";
You will not find anything here:
foreach ($urls as $key => $url) {
$local = [];
// $local does not change here...
// So here $local is an empty array
if (in_array($lowertitle, $local)) {
$lowertitle = $lowertitle.$key;
}
...
If you want to check if the title already exists in the $data array, you have a few options:
You loop over the whole array or use an array filter function to see if the title exists in $data;
You use the lowercase title as the key for your $data array. That way you can easily check for duplicate values.
I would use the second option or something similar to it.
A simple example:
if (array_key_exists($lowertitle, $data)) {
$lowertitle = $lowertitle.$key;
}
...
$data[$lowertitle] = $local;

PHP how to extract info from json string wtihout knowing the keys

I am querying a service if a person have phone number(s) (also maybe not). I have a json string (as return value) like the following:
$json = '{"data":[{"tel1":"1102"},{"tel2":"3220"}],"found":true}';
I convert this string to json_decode() function.
$jd = json_decode($json);
Then I want to get the phone numbers only into an array without keys.
if($jd->found) {
$o2a = get_object_vars($json);
}
var_dump($o2a);
When I want to see what $o2a holds with var_dump() function, I get the following:
array (size=2)
'data' =>
array (size=2)
0 =>
object(stdClass)[2]
public 'tel1' => string '1219' (length=4)
1 =>
object(stdClass)[3]
public 'tel2' => string '2710' (length=4)
'found' => boolean true
I want to get only the phone numbers into an array at the end like:
$phones = array('1219', '2710');
What makes me stop doing this is that I do not know how many phone numbers one can have. Json array could consist of more or less elements.
$possibleJson1 = '{"data":[],"found":false}'; //no phone number found
$possibleJson2 = '{"data":[{"tel1":"1102"},{"tel2":"3220"},{"tel3":"1112"},{"tel4":"3230"}],"found":true}'; //4 phone numbers found
It may vary 0-to-n, so if it was a constant number I could create that array within a loop.
Some functions without any code :)
$json = '{"data":[{"tel1":"1102"},{"tel2":"3220"}],"found":true}';
$vals = array_values(array_reduce(json_decode($json, true)['data'], 'array_merge',[]));
var_dump($vals);
Convert it into an array and then you should be able to iterate it easily
$jd = json_decode($json, true);
$phones = array();
if(isset($jd['data']) && $jd['found']) {
foreach($jd['data'] as $key => $val) $phones[] = $val;
}
Instead of handling with an object, use the second parameter of the json_decode function so it would returned an array.
Check if the data and found keys exist.
Since you don't know what are the keys names, you can use array_values
Demo
.
$jd = json_decode($json, true);
if(isset($jd['data']) && isset($jd['found'])){
$telArr = $jd['data'];
$phones = array();
foreach($telArr as $tel){
$value = array_values($tel);
$phones[] = $value[0];
}
var_dump($phones);
}
Output:
array(2) {
[0]=>
string(4) "1102"
[1]=>
string(4) "3220"
}
Well, I would try something like that:
$json = '{"data":[{"tel1":"1102"},{"tel2":"3220"}],"found":true}';
$jd = json_decode($json);
$phones = [];
if ($jd->found && count($jd->data)) {
foreach ($jd->data as $key -> $value) {
$phones[] = $value;
}
}
Try as using in_array and simple foreach loop
$json = '{"data":[{"tel1":"1102"},{"tel2":"3220"}],"found":true}';
$arr = json_decode($json, true);
$result = array();
if (in_array(true, $arr)) {
foreach ($arr['data'] as $key => $value) {
foreach($value as $k => $v)
$result[] = $v;
}
}
print_r($result);
Fiddle

Categories