The following code returns an associated array with a url,title and snippet from a search engine and it works fine
$js = json_decode($data);
$blekkoArray = array();
$find = array ('http://','https://','www.');
foreach ($js->RESULT as $item)
{
$blekkoArray[$i]['url'] = str_replace ($find, '', ($item->{'url'}) );
$blekkoArray[$i]['title'] = ($item->{'url_title'});
$blekkoArray[$i]['snippet'] = ($item->{'snippet'});
$i++;
}
print_r ($blekkoArray);
I'm trying to add another value to the array so that I can score each element, eg. I want the first result to have a score of 100, the second 99, the third 98 and so on, the following code spits out the same as the above. Therefore I can't seem to add 'score' the the array, any thoughts.
Reagrds
$js = json_decode($data);
$blekkoArray = array();
$find = array ('http://','https://','www.');
foreach ($js->RESULT as $item)
{
$score = 100;
$blekkoArray[$i]['url'] = str_replace ($find, '', ($item->{'url'}) );
$blekkoArray[$i]['title'] = ($item->{'url_title'});
$blekkoArray[$i]['snippet'] = ($item->{'snippet'});
$blekkoArray[$i]['score'];
$i++;
$score--;
}
print_r ($blekkoArray);
You have done 2 mistakes.
1) you have initialized $score inside foreach loop, it should be outside otherwise you will get $score = 100 always.
2) You are not assigning the $score in array,
$score = 100; // move the initialization of $score outside of loop
foreach ($js->RESULT as $item)
{
$blekkoArray[$i]['url'] = str_replace ($find, '', ($item->{'url'}) );
$blekkoArray[$i]['title'] = ($item->{'url_title'});
$blekkoArray[$i]['snippet'] = ($item->{'snippet'});
$blekkoArray[$i]['score'] = $score; // assign the $score value here
$i++;
$score--;
}
OR suggested by u_mulder
$blekkoArray[$i]['score'] = $score--;
Bring the $score = 100; outside of the foreach array. You're resetting it to 100 each loop.
And use
$blekkoArray[$i]['score'] = $score--;
or the same on two lines:
$blekkoArray[$i]['score'] = $score;
$score--;
And next to that, can't you use the key in the foreach? Like this? This is just a guess, as I don't know what $i is. It's not defined or initialised in your code, so...
And a little bonus modification: if you're not using variables as fieldnames, the $var->{'fieldname'} notation can be simplified to $var->fieldname.
All together, this is giving the following code:
$score = 100;
foreach ($js->RESULT as $i => $item)
{
$blekkoArray[$i]['url'] = str_replace ($find, '', $item->url);
$blekkoArray[$i]['title'] = $item->url_title;
$blekkoArray[$i]['snippet'] = $item->snippet;
$blekkoArray[$i]['score'] = $score--;
}
Related
I Want To Get ID From Link i have set all links in array and explode forward slash / and then loop it but i'm getting only one id main link in array
"/4tzCuIpHHhc/long-title-here", i need this id 4tzCuIpHHhc
i'm trying this
<?php
$links = array(
"/WSNINQJZj1s/weightlifting-fairy-kim-bok-ju-ep05-lee-sung-kyung-run-nam-joo-hyuk-errand-20161130",
"/Nmy5FWgX0S0/weightlifting-fairy-kim-bok-ju-ep05-nam-joo-hyuk-reject-a-proposal-20161130",
"/u3gumA7-38A/weightlifting-fairy-kim-bok-ju-ep05-did-you-fall-in-love-with-my-brother-20161130",
"/Zsa_saeRT1E/weightlifting-fairy-kim-bok-ju-ep05-sung-kyung-offered-joo-hyuk-a-deal-20161130",
"/9q0uUfSr0lE/weightlifting-fairy-kim-bok-ju-ep05-nam-joo-hyuks-angry-at-lee-sung-kyung-20161130",
"/UH6YqMDdMDE/weightlifting-fairy-kim-bok-ju-ep05-sung-kyung-and-lee-jae-yoons-drive-date-20161130",
"/5pC2NJtCg_I/weightlifting-fairy-kim-bok-ju-ep03-did-you-fight-because-of-me-20161123",
"/UbxbVugdIdo/weightlifting-fairy-kim-bok-ju-ep01-lee-sung-kyung-fell-into-the-pool-20161116",
"/f29SpSqcOQc/weightlifting-fairy-kim-bok-ju-ep03-lee-sung-kyung-got-into-trouble-20161123",
"/ydWm_Pnp1BQ/weightlifting-fairy-kim-bok-ju-ep04-lee-sung-kyung-vs-nam-joo-hyuk-20161124",
"/uiLlQSexJr4/weightlifting-fairy-kim-bok-ju-ep01-an-underwear-thiefs-identity-20161116",
"/4tzCuIpHHhc/weightlifting-fairy-kim-bok-ju-ep01-weightlifter-vs-rhythmic-gymnast-20161116",
"/QzRi9_4-ItQ/weightlifting-fairy-kim-bok-ju-ep05-lee-sung-kyung-enter-a-contest-instead20161130",
);
foreach ($links as $result) {
$explode_c = explode('/',$result);
$s = $explode_c[1];
}
echo $s;
?>
Make $s as array
foreach ($links as $result) {
$explode_c = explode('/',$result);
$s[] = $explode_c[1];
}
print_r($s);
You can do like this, replace your with below:
$links = array(
"/WSNINQJZj1s/weightlifting-fairy-kim-bok-ju-ep05-lee-sung-kyung-run-nam-joo-hyuk-errand-20161130",
"/Nmy5FWgX0S0/weightlifting-fairy-kim-bok-ju-ep05-nam-joo-hyuk-reject-a-proposal-20161130",
"/u3gumA7-38A/weightlifting-fairy-kim-bok-ju-ep05-did-you-fall-in-love-with-my-brother-20161130",
"/Zsa_saeRT1E/weightlifting-fairy-kim-bok-ju-ep05-sung-kyung-offered-joo-hyuk-a-deal-20161130",
"/9q0uUfSr0lE/weightlifting-fairy-kim-bok-ju-ep05-nam-joo-hyuks-angry-at-lee-sung-kyung-20161130",
"/UH6YqMDdMDE/weightlifting-fairy-kim-bok-ju-ep05-sung-kyung-and-lee-jae-yoons-drive-date-20161130",
"/5pC2NJtCg_I/weightlifting-fairy-kim-bok-ju-ep03-did-you-fight-because-of-me-20161123",
"/UbxbVugdIdo/weightlifting-fairy-kim-bok-ju-ep01-lee-sung-kyung-fell-into-the-pool-20161116",
"/f29SpSqcOQc/weightlifting-fairy-kim-bok-ju-ep03-lee-sung-kyung-got-into-trouble-20161123",
"/ydWm_Pnp1BQ/weightlifting-fairy-kim-bok-ju-ep04-lee-sung-kyung-vs-nam-joo-hyuk-20161124",
"/uiLlQSexJr4/weightlifting-fairy-kim-bok-ju-ep01-an-underwear-thiefs-identity-20161116",
"/4tzCuIpHHhc/weightlifting-fairy-kim-bok-ju-ep01-weightlifter-vs-rhythmic-gymnast-20161116",
"/QzRi9_4-ItQ/weightlifting-fairy-kim-bok-ju-ep05-lee-sung-kyung-enter-a-contest-instead20161130",
);
foreach ($links as $result) {
$explode_c = explode('/',$result);
$s[] = $explode_c[1]; // made array of exploded string
}
echo "<pre>";
print_r($s);
$result = array_search('4tzCuIpHHhc', $s); // search for the string if you need key from $s
echo $id = $s[11];// $result = 11
The following code works and pulls all the images in from the json file.
$content = file_get_contents('URL');
$json = json_decode($content, true);
foreach($json['format'] as $item) {
echo '<img src="' . $item['picture'] . '">';
}
Is there a way that I can have it only grab the last two pictures.
Yes, there is a way.
$result = array_slice($json['format'], -2);
Have a try.
Use this:
$numItems = count(foreach($json['format']);
$i = 0;
foreach($json['format'] as $item) {
if(++$i === $numItems-1) {
result1 = $json['format'][$i]
echo "first picture!";
} if(++$i === $numItems) {
result2 = $json['format'][$i]
echo "second picture!";
}
}
And result1 and result2 is your pictures
You can reverse the order of the array, run it backwards in your foreach loop, grab the first two then break.
$reversed = array_reverse($json);
$counter = 0;
foreach ($reversed['format'] as $item) {
if ($counter == 2) {
break;
}
//your echo image code
++$counter;
}
My version using array_pop:
$content = file_get_contents('URL');
$json = json_decode($content, true);
// take last element of array, array reduces by 1 element
$last = array_pop($json['format']);
print_r($last);
// take last element of array again, array reduces by 1 element
$last = array_pop($json['format']);
print_r($last);
// Beware - using `$json['format']` later means that
// you use array without two last elements
i have this array
$array = array(
"http://www.mywebsite.com/eternal_link_1",
"http://www.mywebsite.com/eternal_link_2/",
"http://www.mywebsite.com/eternal_link_1/#",
"http://subdomain1.mywebwite.com",
"http://subdomain2.mywebwite.com/eternal_link",
"http://www.external-link.com"
);
$eternal_links = array();
$subdomain_links = array();
$external_links = array();
how i can filter $array and add the values to the 3 arrays above?
You can use strpos to find the correct string.
foreach($array as $item){
if(strpos($item, 'external') == TRUE){
array_push($external_links, $item);
}
// and go on..
}
In the following code I simple feed the values of the form
$t = $_GET['type'];
$p = $_GET['product'];
$b = $_GET['brand'];
$c = $_GET['category'];
$attribute = getattributes($p,$b,$c);
$count = count($attribute);
$i=0;
The variable $attribute has
Array([0]=>size [1]=>weight)
Now using the above array i want to generate the following lines
$size = $_GET['size'];
$weight = $_GET['weight'];
I don't want to assign manually just like the above but create the two lines using loops.
Something like
$i=0;
while($i < $count)
{
'$'.$attribute[$i] = '$_GET['.$attribute[$i].']'; //edited part
}
I don't know if this will work, could somebody provide a simple piece of code to achieve the same?
Solution Code:
Awlad Liton: Thank for your answer. There is a minor change in your code which gave the desired output (value form the form)
foreach($attribute as $k => $v){
$$v = $_GET[$v];
}
Try this:
Demo: https://eval.in/96388
$attribute = array(0=>'size', 1=>'weight');
foreach($attribute as $k => $v){
$$v = '$_GET['."'$v'".']';
}
echo $size." ";
echo $weight;
OUTPUT:
$_GET['size'] $_GET['weight']
UPDATE:
as you reply you can do this:
foreach($attribute as $k => $v){
$$v = $_GET[$v];
}
you are almost right. try this:
$$attribute[$i] = $_GET[$attribute[$i]];
http://php.net/manual/en/language.variables.variable.php
I have a string I would like to separate and make a multidimensional array out of. The string looks like this:
$string = "item-size:large,color:blue,material:cotton,item-size:medium,color:red,material:silk,";
Unfortunately, I have no control over how the string is put together, which is why I'm trying to make this array.
My goal is to make an array like this:
$item[1]['color'] // = blue
$item[2]['material'] // = silk
So, here's what I've done:
$item = array();
$i=0; // I know this is messy
$eachitem = explode("item-",$string);
array_shift($eachitem); // get rid of the first empty item
foreach ($eachitem as $values) {
$i++; // Again, very messy
$eachvalue = explode(",",$values);
array_pop($eachvalue); // get rid of the last comma before each new item
foreach ($eachvalue as $key => $value) {
$item[$i][$key] = $value;
}
}
I'm obviously lost with this... any suggestions?
You're mostly there. Just replace your inner foreach with
foreach ($eachvalue as $value) {
$properties = explode(':', $value);
$item[$i][$properties[0]] = $properties[1];
}
You're close, this is how I would do it:
$string = "item-size:large,color:blue,material:cotton,item-size:medium,color:red,material:silk,";
$substr = explode("item-", $string);
$items = array();
foreach ($substr as $string) {
$subitems = array();
$pairs = explode(",", $string);
foreach ($pairs as $pair) {
list($key, $value) = explode(":", $pair, 2);
$subitems[$key] = $value;
}
$items[] = $subitems;
}
var_dump($items);
Using list here is great :) Do note that you would need the extra count limiter in explode else you might lose data if there are more :.
$array = array();
$string = explode(',', $string);
foreach($string as $part):
$part = trim($part);
if(strlen($part) < 3) continue;
$part = explode(':', $part);
$array[$part[0]] = $part[1];
endforeach;
$string = "item-size:large,color:blue,material:cotton,item-size:medium,color:red,material:silk,";
$num_attr = 3;
$item = array();
$i=$x=0;
foreach(explode(',', trim($string,',')) as $attr)
{
list($key, $value) = explode(':', $attr);
$item[$x+=($i%$num_attr==0?1:0)][$key] = $value;
$i++;
}
Set the $num_attr to the number of item attributes in the string (this will allow adjustments in the future if they grow/shrink). The trim inside the foreach is removing ay "empty" data like the last comma (it will also remove a empty first comma if one ever shows up). The crazy looking $item[$x+=($i%$num_attr==0?1:0)] is taking the modulus of the counter / number of attributes which when it is 0 that means we are on a new product line so we add 1 to x which populates the item number index, if the modulus returns a number then we know we are on the same product so we add 0 which doesn't change the items index so that attribute is added on to the same item.