Get last two items of json_decode results with PHP - php

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

Related

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++;
}
}

Multiple json in one foreach

Hey i have five json from all getting information now i encountered with problem like this -> from five different json i need to get latest videoId who newer shows first and all it need put to one function foreach for my too hard i try it do about 5hours and stay in same step
Json 1 json 2
All code need from this two json get latest(newest) videoId in one foreach echo
<?php
$videoList1 = json_decode(file_get_contents('https://www.googleapis.com/youtube/v3/search?order=date&part=snippet&channelId=UCKLObxxmmAN4bBXdRtdqEJA&maxResults=50&key=AIzaSyDVTF2abNVa5pRitb8MVz1ceJFhE-2y_qk'));
$videoList2 = json_decode(file_get_contents('https://www.googleapis.com/youtube/v3/search?order=date&part=snippet&channelId=UCynfZM0Edr9cA4pDymb2rEA&maxResults=50&key=AIzaSyDVTF2abNVa5pRitb8MVz1ceJFhE-2y_qk'));
$i = 0;
foreach($videoList1->items as $item){
if(isset($item->id->videoId)) {
echo $item->id->videoId;
if ( ++$i > 3) {
break;
}
}
}
Tray this:
$videoList1 = json_decode(file_get_contents('https://www.googleapis.com/youtube/v3/search?order=date&part=snippet&channelId=UCKLObxxmmAN4bBXdRtdqEJA&maxResults=50&key=AIzaSyDVTF2abNVa5pRitb8MVz1ceJFhE-2y_qk'),true);
$videoList2 = json_decode(file_get_contents('https://www.googleapis.com/youtube/v3/search?order=date&part=snippet&channelId=UCynfZM0Edr9cA4pDymb2rEA&maxResults=50&key=AIzaSyDVTF2abNVa5pRitb8MVz1ceJFhE-2y_qk'),true);
$videoList = array_merge($videoList1["items"],$videoList2["items"]);
/// sort lastet first
foreach ($videoList as $key => $part) {
$sort[$key] = strtotime($part['snippet']['publishedAt']);
}
array_multisort($sort, SORT_DESC, $videoList);
foreach ($videoList as $video) {
if(isset($video["id"]["videoId"])) {
echo 'publishedAt: '. $video['snippet']['publishedAt'] . ' VideoID: ' . $video["id"]["videoId"] . "\n </br>";
}
}

PHP: show only last data from same data on loop

i have data from php loop foreach like this
foreach ($query->result() as $row) {
echo $row->name;
}
how to make the result show only the end data without remove others if data has same (if data have same value, hide all except the last one) like this:
*sorry bad english, this is the first time i ask here. thank you
Online Check, This is just a demo example.
See below the real example:
At first you need to use array_search for get the position of the same data, if exist then just remove it using $arr[$pos] = '';, and each and every time you need to import data into the new array called $arr and after completing fetching data you need to use a foreach loop to print them.
$arr = array();
foreach($query->result() as $row){
$pos = array_search($row->name, $arr);
if($pos !== false)
$arr[$pos] = '';
$arr[] = $row->name;
}
foreach($arr as $val){
echo $val.'<br/>';
}
Check this and let me know.
The data_seek method might help. This assumes your array is reasonable ordered to begin with.
$rowCount = 0;
$res = $query->result();
foreach($res as $row) {
if ($rowCount < $res->num_rows - 1) {
// set internal pointer to next row
$res->data_seek($rowCount + 1);
// if the row names match, print an empty string
// otherwise print the current name
$nextRow = $res->fetch_row();
if ($row->name == $nextRow->name) {
echo "";
// reset the internal pointer
$res->data_seek($rowCount);
} else {
echo $row->name;
}
} else {
echo $row->name;
}
// update the row count
$rowCount += 1;
}

while foreach loop is outputting twice

I want the loop just to output once. Instead it outputs twice. Here is the code:
$results = mysql_query($query);
while ($c = mysql_fetch_array($results)){
$individualPostcode = explode(",", $c['postcode']);
foreach($individualPostcode as $val){
$val = trim($val); //Get rid of spaces
if($val === $postcode){
echo $c['url']."<br>";
}
}
}
}
Here is the output:
http://www.dyno.com/home-security/local-experts/greater-london/dyno-locks-and-alarms-enfield
http://www.dyno.com/home-security/local-experts/greater-london/dyno-locks--alarms-enfield
http://www.dyno.com/home-security/local-experts/greater-london/dyno-locks-and-alarms-enfield
http://www.dyno.com/home-security/local-experts/greater-london/dyno-locks--alarms-enfield
I've tried taken out the foreach loop but I need to go through that array checking against a user input.
Here is the initialisation of $postcode:
$userInput = $_POST["input"];
if(strlen($userInput) < 4)
echo "User Input : ".$userInput."<br>";
else //Below gets the first three chars of the users string
echo "User Input : $userInput<br>What is being used : ".mb_substr($userInput, 0, 3)."<br>";
$postcode = mb_substr($userInput, 0, 3);
You can always create an array of the URL's to stop them from duplicating by checking if the url has been put into the array:
$results = mysql_query($query);
$urlsArr = array();
while ($c = mysql_fetch_array($results)){
$individualPostcode = explode(",", $c['postcode']);
foreach($individualPostcode as $val){
$val = trim($val); //Get rid of spaces
if($val === $postcode){
if (!in_array($c['url'], $urlsArr)) echo $c['url']."<br>";
$urlsArr[] = $c['url'];
}
}
}
mysql_fetch_array returns both an associative and index array for each of your returned results. The foreach loop is going to loop over both and output twice. Try using mysql_fetch_assoc()
http://php.net/manual/en/function.mysql-fetch-array.php
Better still, try moving to the mysqli class. It's faster and mysql is depricated.
http://php.net/manual/en/intro.mysqli.php

count words of regex pattern in php?

I'm trying to match pattern 'lly' from '/usr/share/dict/words' in linux and I can display them in the browser. I want to count how many words that matches the pattern and display the total at the end of output. This is my php script.
<?php
$dfile = fopen("/usr/share/dict/words", "r");
while(!feof($dfile)) {
$mynextline = fgets($dfile);
if (preg_match("/lly/", $mynextline)) echo "$mynextline<br>";
}
?>
You can use the count function to count how many elements of an array they are. So you simply just add to this array each time, and then count it.
<?php
$dfile = fopen("/usr/share/dict/words", "r");
//Create an empty array
$array_to_count = array();
while(!feof($dfile)) {
$mynextline = fgets($dfile);
if (preg_match("/lly/", $mynextline)){
echo "$mynextline<br>";
//Add it to the array
$array_to_count[] = $mynextline;
}
}
//Now we're at the end so show the amount
echo count($array_to_count);
?>
A simpler way if you don't want to store all of the values (which might come in handy, but anyway) is to just increment to an integer variable like so:
<?php
$dfile = fopen("/usr/share/dict/words", "r");
//Create an integer variable
$count = 0;
while(!feof($dfile)) {
$mynextline = fgets($dfile);
if (preg_match("/lly/", $mynextline)){
echo "$mynextline<br>";
//Add it to the var
$count++;
}
}
//Show the number here
echo $count;
?>
PHP: Glob - Manual
sizeof(glob("/lly/*"));
#edit
Also, you can do like this:
$array = glob("/usr/share/dict/words/lly/*")
foreach ($array as $row)
{
echo $row.'<br>';
}
echo count($array);

Categories