I want import the "links" from a links.txt file and put it on a JSON file but the result is like:
{"domain":[ "www.google.es","www.yahoo.com","www.example.com"],
"id":6
},
{"domain":["www.google.es","www.yahoo.com","www.example.com"],
"id":6
},
{"domain":["www.google.es","www.yahoo.com","www.example.com"],
"id":6
}
Expected:
{"domain":"www.google.es","id":6},
{"domain":"www.yahoo.com"],"id":7},
{"domain":["www.example.com"],"id":8}
As you can see, the id is the same at I want differents id and the links are added 3 times the 3 links and I want add 1 link on 1 option.
<?php
$jsonContents = file_get_contents('data/data.json');
$data = json_decode($jsonContents, true);
$fp = 'links.txt';
$last_item = end($data);
$last_item_id = $last_item['id'];
$contents_arr = file($fp,FILE_IGNORE_NEW_LINES);
foreach($contents_arr as $key=>$value) {
$contents_arr[$key] = rtrim($value, "\r");
$data[] = array(
'domain' => $contents_arr,
'id' => $last_item_id+1,
);
}
$json = json_encode($data);
file_put_contents('data/data.json', $json);
$last_item_id+1 returns $last_item_id+1, it does not change $last_item_id variable.
Dont change $contents_arr array used for loop inside the loop.
You use for domain $contents_arr, which contains all values. Create for domain new array, ie:
foreach($contents_arr as $key=>$value) {
$data[] = array(
'domain' => [rtrim($value, "\r")],
'id' => ++$last_item_id,
);
}
Related
I'm a little confused, and I need help.
I have a foreach loop in my code below. I need to put the foreach loop into the $data = array('image' => $final_image);
How can i put foreach loop in array ? Anyone can help me please.
$getImages = isset($GetNewMessageU['imageid']) ? $GetNewMessageU['imageid'] : NULL;
$ExploreImage = explode(",", $getImages);
$CountExplodes=count($ExploreImage);
foreach($ExploreImage as $a) {
$newdata=$Post->Post_GetUploadChatImageID($a);
if($newdata){
$final_image=$base_url."uploads/images/".$newdata['uploaded_image'];
}
echo $final_image;
}
if($GetNewMessageU){
$json = array();
$data = array(
'image' => $final_image,
);
$result = json_encode( $data );
echo preg_replace('/,\s*"[^"]+":null|"[^"]+":null,?/', '', $result);
}
$getImages = isset($GetNewMessageU['imageid']) ? $GetNewMessageU['imageid'] : NULL;
$ExploreImage = explode(",", $getImages);
$CountExplodes=count($ExploreImage);
// Create an array to store final images
$final_images = [];
foreach($ExploreImage as $a) {
$newdata=$Post->Post_GetUploadChatImageID($a);
if($newdata){
$final_image=$base_url."uploads/images/".$newdata['uploaded_image'];
// Save the image if its new data.
$final_images[]= $final_image;
}
}
if($GetNewMessageU){
$json = array();
$data = array(
'image' => $final_images, // We pass the final images array
);
$result = json_encode( $data );
echo preg_replace('/,\s*"[^"]+":null|"[^"]+":null,?/', '', $result);
}
Made things a bit more verbose.
First define the array.
Then in the if statement add element to the array.
$getImages = isset($GetNewMessageU['imageid']) ? $GetNewMessageU['imageid'] : NULL;
$ExploreImage = explode(",", $getImages);
$CountExplodes=count($ExploreImage);
$final_images = array(); // Define object as array
foreach($ExploreImage as $a) {
$newdata=$Post->Post_GetUploadChatImageID($a);
if($newdata){
$final_image=$base_url."uploads/images/".$newdata['uploaded_image'];
$final_images[] = array('image' => $final_image); // Will create new array item
}
echo $final_image;
}
if($GetNewMessageU){
$json = array();
$data = array(
'image' => $final_image,
);
$result = json_encode( $data );
echo preg_replace('/,\s*"[^"]+":null|"[^"]+":null,?/', '', $result);
}
I've modify this code to get data from a json file instead of xml file (my old code)
<?php
$tracking_id = 'MyID'; //This is used to track the user doing the offer. can be email, clickid, subid.. etc
$userip = $_SERVER['REMOTE_ADDR']; //We need to get the users ip, so the rss feed can display the correct offers for their country.
$user_agent = $_SERVER['HTTP_USER_AGENT']; //lets collect their user agent to pass along.
$max_offers = 5; //max number of offers to display.
$str = file_get_contents('https://www.cpalead.com/dashboard/reports/campaign_json_load_offers.php?id=296213&geoip='.$userip.'&ua='.urlencode($user_agent).'&subid='.urlencode($tracking_id));
$json = json_decode($str, true);
$opOffer = array();
$offer_cnt = 0;
foreach($json['offers'] as $offeritem)
{
$opOffer[$offer_cnt] = array("title" => array($offeritem->title), "link" => array($offeritem->link));
$offer_cnt++;
};
if (0 == count($opOffer)):
echo 'Sorry there are no offers available for your region at this time.';
else:
echo json_encode($opOffer);
endif;
?>
and it's output like this:
[{"title":[null],"link":[null]},{"title":[null],"link":[null]},{"title":[null],"link":[null]},{"title":[null],"link":[null]},{"title":[null],"link":[null]},{"title":[null],"link":[null]},{"title":[null],"link":[null]},{"title":[null],"link":[null]},{"title":[null],"link":[null]},{"title":[null],"link":[null]},{"title":[null],"link":[null]}]
it should be like this:
[{"title":[{"What is Your Favorite Time for McDonald's?"}],"link":[{"https:\/\/filetrkr.com\/show.php?l=0&u=31802&id=5882&tracking_id=MyId"}]}]
Link to see json output: https://www.cpalead.com/dashboard/reports/campaign_json_load_offers.php?id=296213
For the line:
$opOffer[$offer_cnt] = array("title" => array($offeritem->title), "link" => array($offeritem->link));
Shouldn't it be either:
$opOffer[$offer_cnt] = array("title" => $offeritem->title, "link" => $offeritem->link);
or:
$opOffer[$offer_cnt] = array("title" => $offeritem['title'], "link" => $offeritem['link']);
Also, just after the line:
$json = json_decode($str, true);
Add this line and post the results:
echo "<p>JSON: <pre>".print_r($json,true)."</pre></p>";
That last bit to verify you are receiving the JSON you think you should be getting.
I just changed:
$opOffer[$offer_cnt] = array("title" => array($offeritem->title), "link" => array($offeritem->link));
to:
$opOffer[$offer_cnt] = array("title" => array($offeritem["title"]), "link" => array($offeritem["link"]));
And now give me what you want on the JSON:
[{"title":["Amplificador de Bater\u00eda"],"link":["http:\/\/gtrcking.com\/offer.php?id=744798&pub=296213&subid=MyID"]},{"title":["\u0645\u0628\u0627\u0631\u0627\u0629 \u0645\u0630\u0647\u0644\u0629!"],"link":["http:\/\/gtrcking.com\/offer.php?id=550635&pub=296213&subid=MyID"]},....
heres what you want. give that a go.
foreach($json['offers'] as $offeritem)
{
$opOffer[$offer_cnt] = array("title" => array($offeritem['title']), "link" => array($offeritem['link']));
$offer_cnt++;
if ($offer_cnt == $max_offers) break;
};
I have a variable $a='san-serif' and an array Font_list[] now I want only the arrays whose category is 'san-serif' will be filtered. I tried a lot of codes nothing seems working here is my code:-
public function filterFont() {
$a = $_POST['key'];
$url = "https://www.googleapis.com/webfonts/v1/webfonts?key=''";
$result = json_decode(file_get_contents( $url ));
$font_list = "";
foreach ( $result->items as $font )
{
$font_list[] = [
'font_name' => $font->family,
'category' => $font->category,
'variants' => implode(', ', $font->variants),
// subsets
// version
// files
];
}
$filter = filter($font_list);
print_r(array_filter($font_list, $filter));
}
Please help me :-(
What i understood according to that you want something like below:-
<?php
$a='san-serif'; // category you want to search
$font_list=Array('0'=>Array('font_name' => "sans-sherif",'category' => "san-serif"),'1'=>Array('font_name' => "times-new-roman",'category' => "san-serif"),'2'=>Array('font_name' => "sans-sherif",'category' => "roman"));
// your original array seems something like above i mentioned
echo "<pre/>";print_r($font_list); // print original array
$filtered_data = array(); // create new array
foreach($font_list as $key=>$value){ // iterate through original array
if($value['category'] == $a){ // if array category name is equal to serach category name
$filtered_data[$key] = $value; // assign that array to newly created array
}
}
echo "<pre/>";print_r($filtered_data); // print out new array
Output:- https://eval.in/597605
I have inbound return data -> http://php.net/manual/en/function.json-decode.php that is in PhP array format. The file data is the same type. It is just $result from the previous cycle.
$result = api_query("mytrades", array("marketid" => $id));
How do I compare $result array with $file array and then over write FILE with $result data?
In other words, FILE and the data it contains is continuously being updated with $result
compare -> overwrite -> repeat at next execution.
I tried array_diff but it does not like my data types and I cannot find a work around.
Note: .db file is empty at first cycle but becomes populated at first write.
sample code with Array to string conversion error:
<?php
$id = 155;
require_once('phpPlay.php');
$result = api_query("mytrades", array("marketid" => $id));
$lines = file("myDB.db");
$arrayDiffresult = array_diff ( $result, $lines);
var_dump($result);
file_put_contents('myDB.db', print_r($result, true));
?>
var_dump($result);
I think, you looking for some serialization, json_encoding for example.
$result = array(
'return' => array(
array(
"tradeid" =>"74038377",
"tradetype" =>"Sell",
"datetime" =>"2014-11-12 16:05:32",
"tradeprice" =>"0.00675000",
"quantity" =>"22.18670000",
"fee" =>"-0.00007488",
"total" =>"0.14976023",
"initiate_ordertype" =>"Buy",
"order_id" =>"197009493",
),
array(
"tradeid" =>"2",
"tradetype" =>"Sell",
"datetime" =>"2014-11-12 16:05:32",
"tradeprice" =>"0.00675000",
"quantity" =>"22.18670000",
"fee" =>"-0.00007488",
"total" =>"0.14976023",
"initiate_ordertype" =>"Buy",
"order_id" =>"2",
)
)
);
function getdiff($new, $old)
{
//implement right logical diff here
$diff = array();
$old_serialized = array();
foreach ($old as $item) {
$old_serialized[] = json_encode($item);
}
foreach ($new as $item) {
if (in_array(json_encode($item), $old_serialized)) {
continue;
}
$diff[] = $item;
}
return $diff;
}
$old = file_exists('1.db') ? json_decode(file_get_contents('1.db'), 1) : array();
$arrayDiffresult = getdiff($result['return'], $old);
file_put_contents('1.db', json_encode($result['return']));
print_r($arrayDiffresult);
I would like to append html to an item in my array before echoing it on my page and am unsure how to go about doing it.
My data is put into an array like so:
$query = $this->db->get();
foreach ($query->result() as $row) {
$data = array(
'seo_title' => $row->seo_title,
'seo_description' => $row->seo_description,
'seo_keywords' => $row->seo_keywords,
'category' => $row->category,
'title' => $row->title,
'intro' => $row->intro,
'content' => $row->content,
'tags' => $row->tags
);
}
return $data;
I would like to perform the following on my 'tags' before returning the data to my view:
$all_tags = explode( ',' , $row->tags );
foreach ( $all_tags as $one_tag ){
echo '' . $one_tag . '';
The reason for doing this is that the tags in my database contain no html and are simply separated by commas like so news,latest,sports and I want to convert them into
sports ...
My reason for doing this here rather than when I echo the data is that I don't want to repeat myself on every page.
You could just create a function to be used everyhwere you are including tags in your output:
function formatTags($tags) {
$tmp = explode(',', $tags);
$result = "";
foreach ($tmp as $t) {
$result .= sprintf('%s',
urlencode(trim($t)), htmlentities(trim($t)));
}
return $result;
}
And whenever you do something like echo $tags; you do echo formatTags($tags); instead. View code should be separated from model code, which is why I would advise to not put HTML inside your array.
Well first of all you're overwriting $data with every run of the loop so only the final result row will be listed.
Once that's out of the way (fix with $data[] = ...), try this:
...
'tags' => preg_replace( "/(?:^|,)([^,]+)/", "$1", $row->tags);
...