PHP renaming string if string already exists - php

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;

Related

Show only a specific part of html response in php

I am trying to get tracking information from amazon using provided url
https://www.amazon.co.uk/progress-tracker/package/ref=pe_3187911_189395841_TE_typ?_encoding=UTF8&from=gp&itemId=&orderId=203-2171364-3066749&packageIndex=0&shipmentId=23796758607302
I am getting response using file_get_contents() function in php,
what I want is to show only that part of the response which contains the tracking information as an output of my php script and eliminate/hide all the unnecessary content from file_get_contents() response.
One way to do what you're looking for is use DomDocument to filter out the json data in the source ($file) and then use a recursive function to get the elements you need.
You can set the elements you need using an array, $filter. In this example we've taken a sample of some of the available data, i.e. :
$filter = [
'orderId', 'shortStatus', 'promiseMessage',
'lastTransitionPercentComplete', 'lastReachedMilestone', 'shipmentId',
];
The code
<?php
$filename = 'https://www.amazon.co.uk/progress-tracker/package/ref=pe_3187911_189395841_TE_typ?_encoding=UTF8&from=gp&itemId=&orderId=203-2171364-3066749&packageIndex=0&shipmentId=23796758607302';
$file = file_get_contents($filename);
$trackingData = []; // store for order tracking data
$html = new DOMDocument();
#$html->loadHTML($file);
foreach ($html->getElementsByTagName('script') as $a) {
$data = $a->textContent;
if (stripos($data, 'shortStatus') !== false) {
$trackingData = json_decode($data, true);
break;
}
}
// set the items we need
$filter = [
'orderId', 'shortStatus', 'promiseMessage',
'lastTransitionPercentComplete', 'lastReachedMilestone', 'shipmentId',
];
// invoke recursive function to pick up the data items specified in $filter
$result = getTrackingData($filter, $trackingData);
echo '<pre>';
print_r($result);
echo '</pre>';
function getTrackingData(array $filter, array $data, array &$result = []) {
foreach($data as $key => $value) {
if(is_array($value)) {
getTrackingData($filter, $value, $result);
} else {
foreach($filter as $item) {
if($item === $key) {
$result[$key] = $value;
}
}
}
}
return $result;
}
Output:
Array
(
[orderId] => 203-2171364-3066749
[shortStatus] => IN_TRANSIT
[promiseMessage] => Arriving tomorrow by 9 PM
[lastTransitionPercentComplete] => 92
[lastReachedMilestone] => SHIPPED
[shipmentId] => 23796758607302
)
Try this
<?php
$filename = 'https://www.amazon.co.uk/progress-tracker/package/ref=pe_3187911_189395841_TE_typ?_encoding=UTF8&from=gp&itemId=&orderId=203-2171364-3066749&packageIndex=0&shipmentId=23796758607302';
$file = file_get_contents($filename);
$html = new DOMDocument();
#$html->loadHTML($file);
foreach($html->getElementsByTagName('span') as $a) {
$property=$a->getAttribute('id');
if (strpos($property , "primaryStatus"))
print_r($property);
}
?>
It should show "Arriving tomorrow by 9 PM" status.

Remove data from JSON if exact value matches?

This is the part where json gets decoded
$response = file_get_contents("download.json");
$json = json_decode($response, true);
Example of data
{"count":2948,"errors":"","offers":[{"id":"85305","name":"Some Name",
Each of the offers has name
The data goes like this json->offers->name
How to remove all otheroffers if name has been mached with another offer?
And leave only one offer with the same name?
lazy solution:
$arrayFromJson = (json_decode($json));
$offers = [];
$customers = [];
foreach ($arrayFromJson->toppings as $value) {
if(in_array($value->name, $customers)){
continue;
}
$offers[] = $value;
$customers[] = $value->name;
}
$arrayFromJson->toppings = $offers;
let's suppose that the json response file has the following values:
$response = '{"count":2948,"errors":"","offers":[{"id":"1","name":"a"},{"id":"2","name":"b"},{"id":"3","name":"c"},{"id":"4","name":"a"},{"id":"5","name":"c"},{"id":"4","name":"a"},{"id":"4","name":"a"},{"id":"4","name":"b"}]}';
decode them:
$json = json_decode($response, true);
then remove the repeated offers:
// make sure that the required index is exists
if(!empty($json['offers'])){
$json = scan_json_array($json['offers']);
}
by the following recursive function:
function scan_json_array(array $arr, $index = 0){
// if we reached the last element of the array, exit!
if($index == (sizeof($arr)-1)){
return $arr;
}
for(; $index<sizeof($arr);){
$current = $arr[$index];
for($j=$index+1; $j<sizeof($arr); $j++){
$next = $arr[$j];
if($current['name'] === $next['name']){
// remove the matched element
unset($arr[$j]);
// re-index the array
$arr = array_values($arr);
// if it was the last element, increment $index to move forward to the next array element
if($j == (sizeof($arr)-1)){
$index++;
}
return scan_json_array($arr, $index);
}
}
$index++;
}
}

How can I remove specify string words with 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}

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!

Creating array from string

I need to create array like that:
Array('firstkey' => Array('secondkey' => Array('nkey' => ...)))
From this:
firstkey.secondkey.nkey.(...)
$yourString = 'firstkey.secondkey.nkey';
// split the string into pieces
$pieces = explode('.', $yourString);
$result = array();
// $current is a reference to the array in which new elements should be added
$current = &$result;
foreach($pieces as $key){
// add an empty array to the current array
$current[ $key ] = array();
// descend into the new array
$current = &$current[ $key ];
}
//$result contains the array you want
My take on this:
<?php
$theString = "var1.var2.var3.var4";
$theArray = explode(".", $theString); // explode the string into an array, split by "."
$result = array();
$current = &$result; // $current is a reference to the array we want to put a new key into, shifting further up the tree every time we add an array.
while ($key = array_shift($theArray)){ // array_shift() removes the first element of the array, and assigns it to $key. The loop will stop as soon as there are no more items in $theArray.
$current[$key] = array(); // add the new key => value pair
$current = &$current[$key]; // set the reference point to the newly created array.
}
var_dump($result);
?>
With an array_push() in the while loop.
What do you want the value of the deepest key to be?
Try something like:
function dotToArray() {
$result = array();
$keys = explode(".", $str);
while (count($keys) > 0) {
$current = array_pop($keys);
$result = array($current=>$result);
}
return $result;
}

Categories