PHP Add array and loop to code - php

I have a class which is working fine but I need to do multiple results.
Here is the current code:
$url = 'http://mydomain.com';
$keyword = 'somekeyword';
$RankChecker=new RankChecker(1,5);
$result=$RankChecker->find($url,$keyword);
if ($result!==false) {
echo "Your website is found at page number ".$result["page"].".";
}
What is the best way to get it to read multiple url's / keyword's ?

Put the URLs and keywords into an array and loop through it:
$urls = array(
'http://mydomain.com' => 'somekeyword',
'http://myotherdomain.com' => 'someotherkeyword'
);
$RankChecker=new RankChecker(1,5);
foreach($urls as $url => $keyword) {
$result=$RankChecker->find($url,$keyword);
if ($result!==false) {
echo "Website " . $url . " is found at page number ".$result["page"].".";
}
}

Using an array :
<?php
$websites[1] = array('url' => 'http://mydomain.com', 'keyword' => 'somekeyword');
$websites[2] = array('url' => 'http://mydomain2.com', 'keyword' => 'somekeyword2');
$websites[3] = array('url' => 'http://mydomain3.com', 'keyword' => 'somekeyword3');
// etc...
foreach ($websites as $val)
{
$RankChecker=new RankChecker(1,5);
$result=$RankChecker->find($val['url'], $val['keyword']);
if ($result!==false) {
echo "Your website is found at page number ".$result["page"].".";
}
}

Related

Dynamically update a php array with a function

I have multiple sitemaps and I would like to merge them all, but before merging them, I need to append a unique variable to all values in all arrays.
// The global variable
define("BASE_URL", "http://domain.com");
$sitemap_full = [ "home" => BASE_URL ];
// One of the arrays
$sitemap_example = [
"foo" => "/bar",
"gnu" => "/lar"
];
Since I have multiple of those arrays, I wanted to create a function that will append the link.
function pushToSitemap($initial_sitemap, $sitemap) {
foreach ($initial_sitemap as $title => $url) {
return $sitemap[$title] = BASE_URL . $url;
}
}
And in action in will be:
pushToSitemap($sitemap_example, $sitemap_full);
But this just doesn't work because if I print_r($sitemap_full); it will display Array( "home", "http://domain.com" );.
What really annoys me is that if in the function I echo them, they will be echoed.
What am I doing wrong?
EDIT
It should display
Array(
"home" => "http://domain.com"m
"foo" => "http://domain.com/bar",
"gnu" => "http://domain.com/lar
);
Your problem seems lie inside your foreach function:
function pushToSitemap($initial_sitemap, $sitemap) {
foreach ($initial_sitemap as $title => $url) {
return $sitemap[$title] = BASE_URL . $url;
}
}
You are returning just a single item, what's more, the formatting is off.
Instead,
function pushToSitemap($initial_sitemap, $sitemap) {
foreach ($initial_sitemap as $title => $url) {
$sitemap[$title] = BASE_URL . $url;
}
return $sitemap;
}
$sitemap_full = pushToSitemap($sitemap_example, $sitemap_full);

MultiDimensional arrays output

I am currently learning PHP and I am stuck with this problem while testing foreach with multi-dimensional arrays.
Here is my array:
$employees = array(
'Josh' => array(
'age'=>'55',
'salary'=>'105,000',
'hobbies'=> array('none')
),
'John' => array(
'age'=>'45',
'salary'=>'125,000',
'color'=>'red',
'hobbies'=> array('none')
),
'Jane' => array (
'age'=>'25',
'salary'=>'93,000',
'hobbies'=> array ('fishing', 'flying')
)
);
Whenever I try to output I always get an error of Array to string conversion or Invalid argument. Can somebody tell me how could I correctly output this multi-dimensional array using foreach?
If I do it this way, the data like 125,000, basically the value assigned to age and salary isn't written out.
foreach($employees as $names_of_employees=>$data) {
echo $names_of_employees.'<br>';
foreach($data as $specifics=>$values) {
echo $specifics.'<br>';
}
foreach($values as $hobbies) {
echo $hobbies;
}
}
If I do it this way, then it writes out, but as well it writes out "Array" and array to string error:
foreach($employees as $names_of_employees=>$data) {
echo $names_of_employees.'<br>';
foreach($data as $specifics=>$values) {
echo $specifics.$values.'<br>';
}
foreach($values as $hobbies) {
echo $hobbies;
}
}
Thanks.
Try following code
<?php
$employees = array(
'Josh' => array(
'age'=>'55',
'salary'=>'105,000',
'hobbies'=> array('none')
),
'John' => array(
'age'=>'45',
'salary'=>'125,000',
'color'=>'red',
'hobbies'=> array('none')
),
'Jane' => array (
'age'=>'25',
'salary'=>'93,000',
'hobbies'=> array ('fishing', 'flying')
)
);
foreach( $employees as $names_of_employees => $data ){
echo $names_of_employees.'<br>';
echo "Salary: ".$data['salary'].'<br>';
echo "Age: ".$data['age'].'<br>';
if( isset($data['hobbies']) && !empty($data['hobbies']) ) {
echo "Hobbies: ";
foreach( $data['hobbies'] as $hobbies ) {
echo $hobbies.'<br>';
}
}
}
Well, it depends on what you want.
foreach( $employees as $name => $data ){
echo $name;
echo $data['age'];
echo $data['salary'];
// ...etc...
}
It looks like for array element 'John' you've got an extra item in the second dimension. I believe this is ok in PHP but perhaps you have to account for this in the code you use to read the values out.
It is because you are trying to convert an array to a string. The problem is caused by hobbies since it is an array. So in your foreach loop that goes through $data you need to check if it is an array or if the key is equal to hobbies.
foreach($employees as $names_of_employees=>$data) {
echo $names_of_employees.'<br>';
foreach($data as $specifics=>$values) {
if(is_array($values)) { //or you could say if($specifics == 'hobbies')
echo $specifics . ': ' . implode(',',$values) . '<br>';
} else {
echo $specifics . ': ' . $values . '<br>';
}
}
}

Formatting url strings PHP array

Hi all I am sorry if this is a dumb question and I understand I might get banned for asking it but after a lot of work reading over PHP manual, reading the relevant chapters in PHP5.3 and scowering across Stackoverflow I am stuck in my tracks.
I have been universally format the url's taken in from a Search API I have tried to use parse_url(), trim and others unsuccessfully I decided upon str_replace
foreach ($jsonObj->RESULT as $value) {
$BLekko_results[] = array(
'url' => strip_tags($value->url),
'url' => str_replace("http://www.", "http://", $value->url),
'url' => str_replace("https://www.", "http://", $value->url),
'url' => str_replace( " http://", "http://", $value->url),
'url' => str_replace( " http://", "http://", $value->url),
title' => $value->url_title,); }
I plead humbly for you help ...
foreach ($jsonObj->RESULT as $value) {
$url = trim($value->url);
$find = array("http://www.", "https://www.", "https://");
$BLekko_results[] = array(
'url' => str_replace($find, "http://", $url),
'title' => $value->url_title,);
}
Perhaps try something like this:
public function processURLString($urlString) {
$urlString = trim($urlString);
if($urlString) {
$urlString = preg_replace('/https?:\/\//', '', $urlString);
$urlString = trim($urlString);
$urlString = 'http://'.$urlString;
}
return $urlString;
}
And then you can add or remove www etc...
$BLekko_results = array();
foreach ($jsonObj->RESULT as $value) {
$value = strip_tags($value->url);
$updatedURL = str_replace(array('http://www.','https://www.','https://'),"http://",$value->url);
$updatedTitle = $value->url_title;
$BLekko_results[] = array('url'=>$updatedURL,'title'=>$updatedTitle);
}
echo "<pre>";
print_r($BLekko_results);
echo "</pre>";

If array value begins with

I have an array of values.
My crawler scans the web page and inserts all the links, the links' titles and description is a multidimensional array.
But now I have a new array and I only want the links, descriptions and titles etc. if they begin with any value in the array ($bbc_values)
But I don't really know how to do this. I have have gotten pretty far in terms of the actual code but can anyone give me any ideas a) why my code isn't working b) suggestions for my problem?
$bbc_values = array('http://www.bbc.co.uk/news/health-', 'http://www.bbc.co.uk/news/politics-', 'http://www.bbc.co.uk/news/uk-', 'http://www.bbc.co.uk/news/technology-', 'http://www.bbc.co.uk/news/england-', 'http://www.bbc.co.uk/news/northern_ireland-', 'http://www.bbc.co.uk/news/scotland-', 'http://www.bbc.co.uk/news/wales-', 'http://www.bbc.co.uk/news/business-', 'http://www.bbc.co.uk/news/education-', 'http://www.bbc.co.uk/news/science_and_enviroment-', 'http://www.bbc.co.uk/news/entertainment_and_arts-', 'http://edition.cnn.com/');
foreach ($links as $link) {
$output = array(
"title" => Titles($link), //dont know what Titles is, variable or string?
"description" => getMetas($link),
"keywords" => getKeywords($link),
"link" => $link
);
if (empty($output["description"])) {
$output["description"] = getWord($link);
}
}
$data = implode( " , ", $output['link']);
foreach ($output as $new_array) {
if (in_array($output, $bbc_values)) {
$news_stories[] = $new_array;
}
var_dump($news_stories);
}
Okay, I don't completely understand the code here.
But I think $output array should be declared outside the first foreach loop and each array should be appended to it?
Because from the code you're writing, only the details of last $link will be stored inside the $output
Also, what is $data here? what are you using it for?
Turn $bbc_values into a regex:
$bbc_re = '/^('.implode('|', array_map('quotemeta', $bbc_values)).')/';
Then use this regex to filter the links.
foreach ($links as $link) {
if (preg_match($bbc_re, $link)) {
/* Do stuff with $link */
}
}
I assume you what you want is to have an array with links that starts with of the links in the bbc_values and additionally a string $data with a comma separated list of all links. Try something this :
<?php
$bbc_values = array('http://www.bbc.co.uk/news/health-', 'http://www.bbc.co.uk/news/politics-', 'http://www.bbc.co.uk/news/uk-', 'http://www.bbc.co.uk/news/technology-', 'http://www.bbc.co.uk/news/england-', 'http://www.bbc.co.uk/news/northern_ireland-', 'http://www.bbc.co.uk/news/scotland-', 'http://www.bbc.co.uk/news/wales-', 'http://www.bbc.co.uk/news/business-', 'http://www.bbc.co.uk/news/education-', 'http://www.bbc.co.uk/news/science_and_enviroment-', 'http://www.bbc.co.uk/news/entertainment_and_arts-', 'http://edition.cnn.com/');
$news_stories = array();
$all_links = array();
$news_links = array();
foreach ($links as $link) {
$item = array(
"title" => Titles($link),
"description" => getMetas($link),
"keywords" => getKeywords($link),
"link" => $link
);
if (empty($item["description"])) {
$item["description"] = getWord($link);
}
foreach($bbc_values as $bbc_value) {
// note the '===' . this is important
if(strpos($item['link'], $bbc_value) === 0) {
$news_stories []= $item;
$news_links []=$item['link'];
break;
}
}
$all_links[] = $item['link'];
}
$data_all_links = implode(' , ', $all_links);
$data_news_links = implode(' , ', $news_links);
var_dump($news_stories);

Extracting and grouping database data to an array

I have a database field called "servers"
This field has a link in each row, this field content:
> http://www.rapidshare.com/download1
> http://www.rapidshare.com/download2
> http://www.rapidshare.com/download3
> http://www.megaupload.com/download1
> http://www.megaupload.com/download2
> http://www.megaupload.com/download3
> http://www.fileserve.com/download1
> http://www.fileserve.com/download2
> http://www.fileserve.com/download3
I want to create an array with all the server names, and create more array with links inside.
That's how it should be:
$servers = array(
'rapidshare' => array(
'link1' => 'http://www.rapidshare.com/download1',
'link2' => 'http://www.rapidshare.com/download2',
'link3' => 'http://www.rapidshare.com/download3'),
'megaupload' => array(
'link1' => 'http://www.megaupload.com/download1',
'link2' => 'http://www.megaupload.com/download2',
'link3' => 'http://www.megaupload.com/download3'),
'fileserve' => array(
'link1' => 'http://www.megaupload.com/download1',
'link2' => 'http://www.megaupload.com/download2',
'link3' => 'http://www.megaupload.com/download3')
);
This will do the trick: (make sure that domain is actually showing up in $domain variable though because it might be $matches[1]... I can't remember)
$newStructure = array();
foreach($links as $link) {
preg_match("/www\.([^\.])\.com/",$link,$matches);
$domain = $matches[0];
$currentLength = count($newStructure[$domain]);
if($currentLength) {
$newStructure[$domain]['link'.($currentLength+1)] = $link;
} else {
$newStructure[$domain] = array('link1'=>$link);
}
}
$server = array(
'http://www.rapidshare.com/download1',
'http://www.rapidshare.com/download2',
'http://www.rapidshare.com/download3',
'http://www.megaupload.com/download1',
'http://www.megaupload.com/download2',
'http://www.megaupload.com/download3',
'http://www.fileserve.com/download1',
'http://www.fileserve.com/download2',
'http://www.fileserve.com/download3'
);
$match = array();
$myarray = array();
foreach($server as $v) {
// grab server name
preg_match('/\.(.+)\./', $v, $match);
$serverName = $match[1];
// initialize new array if its the first link of that particular server
if (!isset($myarray[$serverName])) {
$myarray[$serverName] = array();
}
// count server array to check how many links are there, and make next link key
$linkKey = 'link' . (count($myarray[$serverName]) + 1);
// store value
$myarray[$serverName][$linkKey] = $v;
}
print_r($myarray);
Hey maybe this will help you. But i dont see the purpose of those names of the keys (link1,link2 etc..). This wont work on pagination thou.

Categories