Unset(remove) array key in php - php

Following is my $newArr0 which is an array of objects.
Array
(
[0] => stdClass Object
(
[created_at] => Mon Dec 08 03:04:47 +0000 2014
[text] => How a individual man can adopt a village in andhra real guds needed hats off to you MASTER BLASTER #Sachin
[source] => Twitter Web Client
)
[1] => stdClass Object
(
[created_at] => Sun Dec 07 17:23:25 +0000 2014
[text] => #two #cool #peoples ..#Coolfieee ..#me nd #Sachin http://t.co/JU971nWAPo
[source] => Instagram
[2] => stdClass Object
(
[created_at] => Sun Dec 07 15:18:22 +0000 2014
[text] => Snga hit 90 odi international fifty...can he hit 6 more to break sachin s fifty record ..#sachin 96 odi fifty ...
kya lgta h tod dega record
[source] => Twitter Web Client
)
[3] => stdClass Object
[created_at] => Sun Dec 07 14:50:53 +0000 2014
[text] => #jeeturaaj Jeeturaaj want #sachin chi book pahje, please give #Sachin #playingitmyway ......:)
[source] => Twitter Web Client
)
[4] => stdClass Object
[created_at] => Sun Dec 07 14:33:49 +0000 2014
[text] => RT #UthMag: Old... http://t.co/b1HMzE3TZI #BCCI #cricket #featured #global #ICC #india #littlemaster #News #ODI #retire #sachin #sports #te…
[source] => Twitter for Android
)
)
I am trying to drop a key with source name from the array, so I tried this code -
foreach ($newArr0 as $nkey1 => $nval1) {
if($nkey1 == "source") {
unset($newArr0["source"]);
}
}
But it is not removing the key, from $newArr0 Let me know what I am doing wrong here.

First off, its a collection of objects inside the array, so you'd use the -> arrow operator on each object inside your loop. Then, alternatively, you could reference each copy of the object inside the foreach and make your unset.
foreach($newArr0 as &$nval1) {
// for each object inside `$newArr0` is in `$nval1`
unset($nval1->source);
// unset $nval1's source
}

<?php
$newArr = array();
foreach ($newArr0 as $key => $value) {
unset($value->source);
$newArr[$key] = $value;
}
$newArr0 = $newArr;
Demo

Here:
foreach ($array as $key => & $object) {
if ($object->source === 'source') {
unset($array[$key]);
}
}

Related

Getting data from a json file with arrays

I'm having troubles to get specific data from a json file using the built-in php functions.
Let me show you some code :
Json File :
{"votes": [ { "date":"November 3rd, 2017 10:08 PM EST", "timestamp":1509743288, "nickname":"Th3ProHack3R", "claimed":"0" }, { "date":"November 3rd, 2017 10:06 PM EST", "timestamp":1509743160, "nickname":"TheKing", "claimed":"0" }, { "date":"November 3rd, 2017 09:45 PM EST", "timestamp":1509741902, "nickname":"some0ne", "claimed":"0" } ] }
My php code :
$json= file_get_contents("myfile.json");
$data = json_decode($json, true);
$voter1 = $data['votes']->nickname;
echo $firstvoter;
I had this code working on a very basic json code without arrays. But something is wrong here because I can't get the nicknames of the voters.
I'm just a little bit confused, so what I wanna do is picking up the nicknames of the voters and then I'll put them on a table using html.
I hope I get a detailed answer so I can understand some of the confusing stuff.
you need to get array to json object. hear "votes" is json object so $data['votes'][0] is return first array see code...
<?php
$json= file_get_contents("myfile.json");
$data = json_decode($json, true);
$voter1 = $data['votes'][0];
$voter2 =$data['votes'][1];
print_r( $voter1);
echo "<br>".$voter1["nickname"];
echo "<br>".$voter2["nickname"];
?>
After converting into json Decode you array make look like this,
Array
(
[votes] => Array
(
[0] => Array
(
[date] => November 3rd, 2017 10:08 PM EST
[timestamp] => 1509743288
[nickname] => Th3ProHack3R
[claimed] => 0
)
[1] => Array
(
[date] => November 3rd, 2017 10:06 PM EST
[timestamp] => 1509743160
[nickname] => TheKing
[claimed] => 0
)
[2] => Array
(
[date] => November 3rd, 2017 09:45 PM EST
[timestamp] => 1509741902
[nickname] => some0ne
[claimed] => 0
)
)
)
In this you need the nickname:
foreach ($jsonData['votes'] as $key => $value) {
echo "Nickname : ". $value['nickname']."<br/>";
}

using usort on simpleXML that's been converted to an array

I have read a standard RSS feed into simpleXML and get the following after converting to an array:
[0] => SimpleXMLElement Object (
[guid] => https://www.zazzle.com/scissors_by_any_other_name_dreadful_pun_t_shirt-235586301981812394
[pubDate] => Wed, 23 Aug 2017 13:41:08 GMT
[title] => SimpleXMLElement Object ( )
[link] => https://www.zazzle.com/scissors_by_any_other_name_dreadful_pun_t_shirt-235586301981812394
[author] => HightonRidley
[description] => SimpleXMLElement Object ( )
[price] => $30.15
)
[1] => SimpleXMLElement Object (
[guid] => {not enough reputation points to show link}
[pubDate] => Sat, 19 Aug 2017 15:53:19 GMT
[title] => SimpleXMLElement Object ( )
[link] => {not enough reputation points to show link}
[author] => HightonRidley
[description] => SimpleXMLElement Object ( )
[price] => $15.65 )
)
This is the code used to create and display the above
$sortable = array();
foreach($product_grid->channel->item as $node) {
$sortable[] = $node;
}
print_r($sortable);
To prove to myself it's working and accessible as intended I used this
foreach ($sortable as $rssitem) {
echo "<br>" . $rssitem->pubDate;
}
echo "<br>".$sortable[0]->pubDate;
echo "<br>".$sortable[1]->pubDate;
and got this output
Wed, 23 Aug 2017 13:41:08 GMT
Sat, 19 Aug 2017 15:53:19 GMT
Wed, 23 Aug 2017 13:41:08 GMT
Sat, 19 Aug 2017 15:53:19 GMT
...but when I try to sort using usort, I get no output and Firefox console tells me I have a server error 500
Here's how I'm using usort
usort($sortable, function($a, $b)
{
return strtotime($a->pubDate) > strtotime($b->pubDate);
});
I've checked various questions/answers on using usort here and as many other places as I can find online but to no avail.
Can someone please tell me how to reference the various elements of $sortable from within that anonymous function. I will be doing other sorts using other elements once I get this first one cracked.
Thanks!

Remove array index based on date

I am working with Symfony framework and I have a Controller whose job is to fetch the RSS feeds.
Once I have the fetched feeds in a set of array, I would like to remove those feeds whose date is greater than the date I provide.
So this is the array of object that I get when I fetch the feeds
Array
(
[0] => AppBundle\Entity\Rss Object
(
[id:AppBundle\Entity\Rss:private] =>
[feedItemTitle:AppBundle\Entity\Rss:private] => Project Manager, Investments Business Management - Prudential - Madison, NJ
[feedItemDescription:AppBundle\Entity\Rss:private] => Globally, PREI has offices in Munich, Frankfurt, London, Paris, Luxembourg, Singapore, Seoul, Tokyo, Sydney, and Mexico City....
From Prudential - 30 Jul 2015 20:00:31 GMT
- View all Madison jobs
[feedItemLink:AppBundle\Entity\Rss:private] => http://www.indeed.com/job/Project-Manager-at-Prudential-in-Madison,-NJ-27eedeae3104d1be
[feedItemPubDate:AppBundle\Entity\Rss:private] => DateTime Object
(
[date] => 2015-07-30 20:00:31.000000
[timezone_type] => 1
[timezone] => +00:00
)
)
[1] => AppBundle\Entity\Rss Object
(
[id:AppBundle\Entity\Rss:private] =>
[feedItemTitle:AppBundle\Entity\Rss:private] => Client Services Specialist - Prudential - Madison, NJ
[feedItemDescription:AppBundle\Entity\Rss:private] => Globally, PREI has offices in Munich, Frankfurt, London, Paris, Luxembourg, Singapore, Seoul, Tokyo, Sydney, and Mexico City....
From Prudential - 03 Aug 2015 19:59:34 GMT
- View all Madison jobs
[feedItemLink:AppBundle\Entity\Rss:private] => http://www.indeed.com/job/Client-Service-Specialist-at-Prudential-in-Madison,-NJ-51ad596876a01466
[feedItemPubDate:AppBundle\Entity\Rss:private] => DateTime Object
(
[date] => 2015-08-03 19:59:34.000000
[timezone_type] => 1
[timezone] => +00:00
)
)
[2] => AppBundle\Entity\Rss Object
(
[id:AppBundle\Entity\Rss:private] =>
[feedItemTitle:AppBundle\Entity\Rss:private] => Manager, Client Services - Prudential - Madison, NJ
[feedItemDescription:AppBundle\Entity\Rss:private] => Globally, PREI has offices in Munich, Frankfurt, London, Paris, Luxembourg, Singapore, Seoul, Tokyo, Sydney, and Mexico City....
From Prudential - 03 Aug 2015 19:59:32 GMT
- View all Madison jobs
[feedItemLink:AppBundle\Entity\Rss:private] => http://www.indeed.com/job/Manager-at-Prudential-in-Madison,-NJ-c0452d58384711e7
[feedItemPubDate:AppBundle\Entity\Rss:private] => DateTime Object
(
[date] => 2015-08-03 19:59:32.000000
[timezone_type] => 1
[timezone] => +00:00
)
)
[3] => AppBundle\Entity\Rss Object
(
[id:AppBundle\Entity\Rss:private] =>
[feedItemTitle:AppBundle\Entity\Rss:private] => Technical Sales Representative, Cell Culture Products - STEMCELL Technologies Inc - United States
[feedItemDescription:AppBundle\Entity\Rss:private] => We create novel, useful, standardized products of unfailing quality and deliver them to more than 70 countries via our many regional offices plus distribution...
From STEMCELL Technologies Inc - 01 Aug 2015 01:16:36 GMT
- View all jobs
[feedItemLink:AppBundle\Entity\Rss:private] => http://www.indeed.com/job/Technical-Sales-Representative-at-STEMCELL-Technologies-in-United-States-f4c10a0e10852686
[feedItemPubDate:AppBundle\Entity\Rss:private] => DateTime Object
(
[date] => 2015-08-01 01:16:36.000000
[timezone_type] => 1
[timezone] => +00:00
)
)
[4] => AppBundle\Entity\Rss Object
(
[id:AppBundle\Entity\Rss:private] =>
[feedItemTitle:AppBundle\Entity\Rss:private] => Technical Sales Representative, Cell Separation Products - STEMCELL Technologies Inc - United States
[feedItemDescription:AppBundle\Entity\Rss:private] => We create novel, useful, standardized products of unfailing quality and deliver them to more than 70 countries via our many regional offices plus distribution...
From STEMCELL Technologies Inc - 31 Jul 2015 01:13:35 GMT
- View all jobs
[feedItemLink:AppBundle\Entity\Rss:private] => http://www.indeed.com/job/Technical-Sales-Representative-at-STEMCELL-Technologies-in-United-States-b8c62120268afb55
[feedItemPubDate:AppBundle\Entity\Rss:private] => DateTime Object
(
[date] => 2015-07-31 01:13:35.000000
[timezone_type] => 1
[timezone] => +00:00
)
)
[5] => AppBundle\Entity\Rss Object
(
[id:AppBundle\Entity\Rss:private] =>
[feedItemTitle:AppBundle\Entity\Rss:private] => Accounting Intern - Code Corp - Draper, UT
[feedItemDescription:AppBundle\Entity\Rss:private] => Would love someone that is interested in International Accounting processes because this position will work with our China, Singapore & Europe office....
From Code Corp - 31 Jul 2015 21:13:43 GMT
- View all Draper jobs
[feedItemLink:AppBundle\Entity\Rss:private] => http://www.indeed.com/job/Accounting-Intern-at-Code-in-Draper,-UT-0e0aca45e988cc89
[feedItemPubDate:AppBundle\Entity\Rss:private] => DateTime Object
(
[date] => 2015-07-31 21:13:43.000000
[timezone_type] => 1
[timezone] => +00:00
)
)
)
As you will notice date in above array.
I am passing the above array and date (not the date from an array above but the $date that i would like to match the array date with to exclude the feed or not) in a parameter to a function below
public function isValid($feed, $date)
{
foreach ($feed as $item) {
if ($item->getfeedItemPubDate()->date < $date) {
echo $item->getfeedItemPubDate()->date;
echo "<br>";
}
}
}
I am able to get the list of feeds whose date from array are smaller than $date but what I am stuck at is how to remove those feeds from the array ? and then pass back the new set of array back to the controller.
You can remove array item by unset function. To know key of that item change a little foreach loop. As so, for example
public function isValid($feed, $date)
{
foreach ($feed as $key => $item)
if ($item->getfeedItemPubDate()->date < $date)
unset ($feed[$key]);
}
You can also try the array_filter function to which you provide a callback function, in your case something like
$feed = array_filter($feed, function($item) use($date) {
return ($item->getfeedItemPubDate()->date < $date);
});
where $date is a variable you set before
Try:
public function isValid($feed, $date)
{
foreach ($feed as $item) {
if (strtotime($item->getfeedItemPubDate()->date) < strtotime($date)) {
echo $item->getfeedItemPubDate()->date;
echo "<br>";
}
}
}

Getting values from specified keys

i use imdb api
$homepage = file_get_contents('http://www.imdbapi.com/?i='.$imdbID);
$arr = json_decode($homepage);
In $arr i have all data about related movie.
Maguire [Year] => 1996 [Rated] => R [Released] => 13 Dec 1996 [Genre] => Comedy, Drama, Romance, Sport [Director] => Cameron Crowe [Writer] => Cameron Crowe [Actors] => Tom Cruise, Cuba Gooding Jr., Renée Zellweger, Kelly Preston [Plot] => When a sports agent has a moral epiphany and is fired for expressing it, he decides to put his new philosophy to the test as an independent with the only athlete who stays with him. [Poster] => http://ia.media-imdb.com/images/M/MV5BMTkxNjc2NjQwOF5BMl5BanBnXkFtZTcwMDE2NDU2MQ##._V1_SX320.jpg [Runtime] => 2 hrs 19 mins [Rating] => 7.2 [Votes] => 97329 [ID] => tt0116695 [Response] => True )
what i want is that reaching specified key's value.
Is there a function like that? For example , i will give the key=> Actors and get all actors?
:/ Like this?
$homepage = file_get_contents('http://www.imdbapi.com/?i='.$imdbID);
$arr = json_decode($homepage, true);
print($arr['Actors']);

Insert element into order position of array?

All values of array $A are string the same length.
$A = Array
(
[0] => 03
[1] => 04
[2] => 05
[3] => 06
// [4] => 07 // "07" before "04" position
[4] => 04
[5] => 05
[6] => 06
// [8] => 07 // "07" before "08" position
[7] => 08
[8] => 03
[9] => 04
[10] => 05
[11] => 06
[12] => 07 // it is existing
[13] => 08
) ;
I want to Insert the "07" element if it is not existing before "04" or "08" position.start from position 1
So It will be after changed
$A = Array
(
[0] => 03
[1] => 04
[2] => 05
[3] => 06
[4] => 07 // just appended
[5] => 04
[6] => 05
[7] => 06
[8] => 07 // just append
[9] => 08
[10] => 03
[11] => 04
[12] => 05
[13] => 06
[14] => 07
[15] => 08
) ;
Anybody know how to do this ,help me please?
There would be "prettier" ways to do this but, as intended...
iterate the array
if the current value is equal to 7 minus 1 you will insert a new value there
create a function "insert_into_array" that:
a) Splits your array in two (look at array_chunk)
b) POPs your element to the end of the first array (array_pop)
c) merges your two arrays back (array_merge)
I've abstained from writing any code as this is probably homework and, writing code, even if you're not really deep thinking the problem will push you a long way to passing the exam...
not the most beautiful solution, but should do the job:
$b = array();
for($i=0;$i<count($A);$i++){
$b[] = $A[$i];
if(($i<count($A) - 1) && ($A[$i+1]<$A[$i] || ($A[$i+1] == '08')) && $A[$i] < '07')
$b[] = '07';
}
var_dump($b);
First, find the gaps in your array, that is the positions where there's 06 but not a following 07:
$positions = array();
foreach ($A as $k => $v) {
if (isset($last) && $last != $v - 1 && $last == '06') {
$positions[] = $k;
}
$last = $v;
}
Then, insert them:
$count = 0;
foreach ($positions as $pos) {
array_splice($A, $pos + ($count++), 0, '07');
}
That's it.
//make sure the array is numeric:
$A = array_values($A);
foreach(array('04','08') as $search){
$positions = array_keys($A,$search);
rsort($positions);
foreach($positions as $key){
if($key==0 || $A[$key-1] != '07'){
array_splice($A,$key,0,'O7');
}
}
}
In 2017, I've found 2 beautiful methods that is part of nette\utils package.
Arrays::insertBefore()
Arrays::insertAfter()
They do job perfectly!
Just run:
composer require nette/utils
and use Arrays class or inspire in their code.

Categories