How to deal with array of multidimensional arrays - php

I have the below array containing arrays and arrays. This is just one entry; imagine now that I have 20 sources and each source contains at least 10 entries like the one below. This is a nightmare I want to solve.
Can anyone advice on how I can parse this efficiently in PHP and be able to get each of the values to be able to insert them into a DB for further processing!! Thank you.
Array (
[id] => id
[direction] => ltr
[updated] => 1407220315278
[title] => Syria | The Guardian
[alternate] => Array ( [0] => Array (
[href] => href
[type] => text/html ) )
[continuation] => 147a4ddf48e:28d98:bda086f
[items] => Array ( [0] => Array (
[keywords] => Array (
[0] => Global development
[1] => Refugees
[2] => Syria
[3] => Middle East and North Africa
[4] => World news
[5] => UK news
[6] => Scotland
[7] => Conflict and development
[8] => Immigration and asylum )
[fingerprint] => 47075b4f
[originId] => originId
[id] => Te6w3H2VbpKKFda+uYdqytnutphL/kktv0RL7gq9jjU=_147a4ddf48e:28d98:bda086f
[title] => A Syrian refugee in Scotland: 'I'm one of the lucky ones' video
[published] => 1407218400000
[crawled] => 1407220315278
[alternate] => Array (
[0] => Array (
[href] => href
[type] => text/html ) )
[author] => Produced by Claudine Spera and Ellie Violet Bramley
[origin] => Array (
[streamId] => streamId
[title] => Syria | The Guardian
[htmlUrl] => htmlUrl )
[summary] => Array (
[direction] => ltr
[content] => Ayman is one of about 3 million Syrian refugees living outside his homeland. After nine of his friends were killed in Damascus, Ayman used his student visa to flee to the UK, leaving his wife and twin boys behind. 'We didn't expect civil war in Syria, never, ever,' he says. But now, with the help of the Red Cross, the family are reunited and building a life in Edinburgh Continue reading... )
[visual] => Array (
[url] => imagUrl
[height] => 252
[width] => 600
[contentType] => image/jpeg )
[unread] => 1
[categories] => Array (
[0] => Array (
[id] => user/5312f2fe-1adc-476f-93da-8b1db5a63180/category/عربي
[label] => عربي ) )
[engagement] => 4 [engagementRate] => 0.33 ) ) )

If there are always the same keys in the array it should be relatively easy to iterate with something like this:
foreach($yourarray as $key1=>$item1){
//dosomething
if($key1=="alternate"){
foreach($item1 as $key2=>$item2){
//and so on
}
}
}
As to saving it in a database I admit its not easy and I am not that experienced with databases but if I were you I'd save them in multiple tables with "1 to n" references.

Related

Displaying parts of an API Array with PHP

So I'm working with an API for vehicles, and I am running into a wall and hoping to get some input from those with more experience with this... I'll start by showing an example of the data I get back from an API call.
Array
(
[make] => Array
(
[id] => 200003644
[name] => Chrysler
[niceName] => chrysler
)
[model] => Array
(
[id] => Chrysler_200
[name] => 200
[niceName] => 200
)
[engine] => Array
(
[equipmentType] => ENGINE
[availability] => USED
[cylinder] => 6
[size] => 3.6
[configuration] => V
[fuelType] => flex-fuel (unleaded/E85)
[horsepower] => 295
[type] => flex-fuel (FFV)
[code] => ERB
[rpm] => Array
(
[horsepower] => 6350
[torque] => 4250
)
[valve] => Array
(
[gear] => double overhead camshaft
)
)
[transmission] => Array
(
[equipmentType] => TRANSMISSION
[availability] => USED
[transmissionType] => AUTOMATIC
)
[drivenWheels] => front wheel drive
[numOfDoors] => 4
[options] => Array
(
[0] => Array
(
[category] => Safety
[options] => Array
(
[0] => Array
(
[id] => 200741607
[name] => SafetyTec
[description] => Adaptive Cruise Control with Stop & Go; Advanced Brake Assist; Automatic high beam control; Blind Spot and Cross Path Detection; Full Speed Forward Collision Warning Plus; Lane Departure Warning Plus; Parallel and Perpendicular Park Assist with Stop; Rain sensitive windshield wipers
[equipmentType] => OPTION
[availability] => All C/All C Platinum
)
)
)
[1] => Array
(
[category] => Package
[options] => Array
(
[0] => Array
(
[id] => 200741480
[name] => Quick Order Package 26N (Fleet)
[description] => Vehicle with standard equipment
[equipmentType] => OPTION
[availability] => All C
)
[1] => Array
(
[id] => 200741610
[name] => Premium Group
[description] => 115V auxiliary power outlet; Exterior mirrors with memory; Heated 2 tone leather steering wheel; Luxury door trim panel; Premium leather trimmed ventilated front seats with leather seat cushion; Radio/driver seat/Climate control with memory; Real wood/bronze chrome interior accents
[equipmentType] => OPTION
[availability] => All C/All C Platinum
)
[2] => Array
(
[id] => 200741715
[name] => Premium Lighting Group
[description] => HID headlamps with LED daytime running lights; LED fog lamps
[equipmentType] => OPTION
[availability] => All S/All C
)
[3] => Array
(
[id] => 200741805
[name] => Navigation And Sound Group I
[description] => 506 watt amplifier; SiriusXM traffic with 5-year of included service; Travel Link Service with 5-year of included service; 9 amplified speakers with subwoofer; GPS navigation; HD radio; Uconnect 8.4AN AM/FM/SiriusXM/Hard disc drive/Bluetooth/Navigation
[equipmentType] => OPTION
[availability] => All C
)
)
)
)
So if I have this data stored in a variable called $data for example, I can do something like this and it works:
foreach ($data['options'] as $options) {
echo $options['category'];
}
That will return me "Safety", and "Package".
However, if I wanted to get the vehicle's make and I do something like this:
foreach ($data['make'] as $make) {
echo $make['name'];
}
It just returns me the value : Cc (Upper case C from the make name, and lowercase c from the make niceName). Why is it doing this? What am I doing wrong?
Thank you!
There's only one 'make', so I think you just want this (no loop):
echo $data['make']['name'];
Every element of $data['make'] is a string (maybe integer), but not an array as every element of $data['options']. So, you can't use [] notation in case of $data['make'].
Just:
foreach ($data['make'] as $make) {
echo $make;
}
will do what you need.

PhP - Search massive array for value, return parent key.

Q: How to Search Massive Multi-Dimensional Array for Single Value, and Return Parent Array?
I have this massive json that represents all of the achievements in WoW.
http://us.battle.net/api/wow/data/character/achievements
I converted it into an array using json_decode. This then leaves me with a very massive array that I need to search all of its levels until I find a specific value, I then need to return the parent array of that value.
ex:
This is one small part of the decoded array.
[0] => Array
(
[id] => 7385
[title] => Pub Crawl
[points] => 10
[description] => Complete the Brewmaster scenario achievements listed below.
[reward] => Reward: Honorary Brewmaster Keg
[rewardItems] => Array
(
[0] => Array
(
[id] => 87528
[name] => Honorary Brewmaster Keg
[icon] => inv_holiday_brewfestbuff_01
[quality] => 3
[itemLevel] => 90
[tooltipParams] => Array
(
)
[stats] => Array
(
)
[armor] => 0
)
)
[icon] => inv_misc_archaeology_vrykuldrinkinghorn
[criteria] => Array
(
[0] => Array
(
[id] => 20680
[description] => Spell No Evil
[orderIndex] => 0
[max] => 1
)
[1] => Array
(
[id] => 20681
[description] => Yaungolian Barbecue
[orderIndex] => 1
[max] => 1
)
[2] => Array
(
[id] => 20682
[description] => Binan Village All-Star
[orderIndex] => 2
[max] => 1
)
[3] => Array
(
[id] => 20683
[description] => The Keg Runner
[orderIndex] => 3
[max] => 1
)
[4] => Array
(
[id] => 20684
[description] => Monkey in the Middle
[orderIndex] => 4
[max] => 1
)
[5] => Array
(
[id] => 20685
[description] => Monkey See, Monkey Kill
[orderIndex] => 5
[max] => 1
)
[6] => Array
(
[id] => 20686
[description] => Don't Shake the Keg
[orderIndex] => 6
[max] => 1
)
[7] => Array
(
[id] => 20687
[description] => Party of Six
[orderIndex] => 7
[max] => 1
)
[8] => Array
(
[id] => 20688
[description] => The Perfect Pour
[orderIndex] => 8
[max] => 1
)
[9] => Array
( re
[id] => 20689
[description] => Save it for Later
[orderIndex] => 9
[max] => 1
)
[10] => Array
(
[id] => 20690
[description] => Perfect Delivery
[orderIndex] => 10
[max] => 1
)
)
[accountWide] =>
[factionId] => 2
)
I am attempting to create a function where I can just simply enter the achievement ID, which in this exmple is 7385, and have the parent array which would be [0] => Array (...); returned, so i can then grab the achievement details from that array.
I am not sure if this is really a proper question, as I am not sure as where to start.
So far I have just started breaking the original massive array down into its 10 equally as massive categories, and then searching them each individually, but I would like to just be able to search the main array once instead of searching each category array individually.
ex:
$allAchieves = file_get_contents('http://us.battle.net/api/wow/data/character/achievements');
$allAchieves = json_decode($allAchieves, true);
$generalAchieves = $allAchieves[achievements][0][achievements];
$quests = $allAchieves[achievements][1][categories];
$explorationAchieves = $allAchieves[achievements][2][categories];
$pvp = $allAchieves[achievements][3][categories];
$dungeonAndRaids = $allAchieves[achievements][4][categories];
$professions = $allAchieves[achievements][5][categories];
$reputation = $allAchieves[achievements][6][categories];
$scenarios = $allAchieves[achievements][7][categories];
$worldEvents = $allAchieves[achievements][8][categories];
$petbattle = $allAchieves[achievements][9][categories];
$featsOfStrength = $allAchieves[achievements][10][categories];
Hopefully someone can help, as the other threads I have seen sofar on array searching seem too simple to be of any help as the arrays they are dealing with are nothing to the size of the one I have here.
Thanks for the suggestions, but I solved the issue using a different approach found here:
http://us.battle.net/wow/en/forum/topic/8892160022?page=1#4

What is the correct way to write an SQL statement to push data rows for this array?

I am trying to push array data to a MySQL database using foreach(). I'm quite a novice at PHP & mysql, so been working through parsing this data to PHP from an Ajax script, now just need to manipulate the data.
What is the correct syntax to push this data into SQL so that each dataset in the array goes to a seperate row?
i am trying to use foreach, but the complexity is that the array itself can change in size and the second complexity is that the data itself may be refreshed (i.e same id new values on a new day), so I want to build in some intelligence to update info not just append; and also to backup old data to another table.
is this syntax correct?
$sql = "INSERT INTO table1 (col1, col2) VALUES ";
foreach($rows as $i=>$row) {
if ($i>0) {
$sql .= sprintf(",(%s,%s)", $row["col1_value"], $row["col2_value"]);
} else {
$sql .= sprintf("(%s,%s)", $row["col1_value"], $row["col2_value"]);
}
}
mysql_query($sql);
The data in the array is as follows - this is only part of a multidimensional array, but I have figured out how to manipulate the rest of the array to my needs.
The only other thing I need to do is figure out a way to take the coords field and manipulate it as follows
Extract x & y data from coords
Multiple x & y by 600/386
Reverse x & y and take the first digit of each coordinate to create a new value y[1]x[1].
For this I tried just on the first data set, as follows, but I am inexperienced in data handling on PHP. Pretty sure it is wrong.
$testcoords = $_POST['data'][0]['coords'];
list($x,$y) = explode(“:”,str_replace(“’”,“”,$testcoords));
$xtrans = number_format($x*600/386,$decimals=null);
$ytrans = number_format($y*600/386,$decimals=null);
$cont = “C”.$ytrans[0].$xtrans[0]
So to summarize, three questions
How do I transfer data into a table, with rows for each individual dataset in the [data] array?
How do overwrite and archive any existing values in the table rather than simply concatenating?
How do I manipulate one specific string to return a custom variable as defined above?
[data_type] => city
[data] => Array
(
[0] => Array
(
[id] => 16515340
[owner_id] => 3475
[owner] => Player1
[coords] => '268:252
[name] => AC2013
[score] => 11863
[city_type] => castle
[location] => land
)
[1] => Array
(
[id] => 16515335
[owner_id] => 3475
[owner] => Player1
[coords] => '263:252
[name] => AC2013
[score] => 7
[city_type] => castle
[location] => water
)
[2] => Array
(
[id] => 17891610
[owner_id] => 3523
[owner] => Player2
[coords] => '282:273
[name] => City of Repoman9900
[score] => 1978
[city_type] => castle
[location] => water
)
[3] => Array
(
[id] => 10616856
[owner_id] => 73
[owner] => Player2
[coords] => '024:162
[name] => 1killer
[score] => 1308
[city_type] => castle
[location] => water
)
[4] => Array
(
[id] => 10813465
[owner_id] => 2862
[owner] => Player3
[coords] => '025:165
[name] => City of vuvuzea991
[score] => 1091
[city_type] => castle
[location] => land
)
[5] => Array
(
[id] => 17367317
[owner_id] => 84
[owner] => Player4
[coords] => '277:265
[name] => Dreadland
[score] => 776
[city_type] => castle
[location] => water
)
[6] => Array
(
[id] => 2162850
[owner_id] => 2989
[owner] => Player5
[coords] => '162:033
[name] => City of Dinoeyez
[score] => 157
[city_type] => castle
[location] => water
)
[7] => Array
(
[id] => 2818192
[owner_id] => 556
[owner] => Player6
[coords] => '144:043
[name] => City of wildfire123
[score] => 7
[city_type] => castle
[location] => water
)
)
[sender] => Array
(
[world] => Array
(
[id] => 232
[name] => Server 4
[number] => NaN
)
[alliance] => Array
(
[id] => 2
[name] => Alliance2
)
[player] => Array
(
[id] => 98
[name] => SuperUser
)
[browser] => Array
(
[type] => Chrome
[version] => 25.0.1364.160
)
[aix_version] => 1.00
)
)
The problems I see:
foreach($rows as $i=>$row) {
$sql = "INSERT INTO table1 (col1, col2) VALUES "; //reinitialize here.
if ($i>0) { //Why have the if statement, the results of the conditions are the same.
$sql .= sprintf("('%s','%s')", $row["col1_value"], $row["col2_value"]); //add quotation marks for string values, remove the comma.
} else {
$sql .= sprintf("(%s,%s)", $row["col1_value"], $row["col2_value"]);
}
mysql_query($sql); //execute the statement here.
}
Your other questions:
How do overwrite and archive any existing values in the table rather than simply concatenating?
To overwrite you do an update statement, the MySql website gives hints to syntax.
To archive, you will need to create an archive table that is pretty much a duplicate of the table being archived and insert/update that table.
In this context, I am not sure what you mean by concatenation, it does not really apply to databases that are normalized.
How do I manipulate one specific string to return a custom variable as defined above?
Ah gonna skip that one, it is a lot to ask in one post.

Codeigniter: Referencing a specific array index returned in model result

I'm still trying to wrap my head around passing db query results from a model back to controller and finally to a view. I seem to be getting the data to the right place, I'm just not sure how to best access the resulting array of objects in the view.
Specifically, I'm trying to query my db for the most recent 7 distinct dates that someone has submitted a link. I get back an array of dates, and then for each of those dates I do a query for all links submitted on that date and store the results in an array. Then in the view, for each of those distinct dates, I show a header (the date), immediately followed by the links associated with it.
The array that come from my distinct date query ($link_headers):
Array (
[0] => stdClass Object([added_date] => 2011-08-11)
[1] => stdClass Object([added_date] => 2011-05-03)
[2] => stdClass Object([added_date] => 2011-04-21)
[3] => stdClass Object([added_date] => 2011-04-10)
[4] => stdClass Object([added_date] => 2011-03-04)
[5] => stdClass Object([added_date] => 2011-02-28)
[6] => stdClass Object([added_date] => 2011-02-22)
)
The array that comes from my query for actual links submitted ($links_result):
Array
(
[0] => Array
(
[0] => stdClass Object
(
[user_id] => 2
[link_id] => 1178
[link_url] => http://www.amazon.com/Silicone-Rubber-CASSETTE-Design-IPHONE/dp/B004YDJWOY
[link_name] => Silicone Skin BLACK CASSETTE TAPE
[link_notes] => iPhone case... probably won't fit in my dock.
[added_date] => 2011-08-11
[flag_new] => 1
[rating] => 4
[public] => 1
)
)
[1] => Array
(
[0] => stdClass Object
(
[user_id] => 2
[link_id] => 1177
[link_url] => http://snorby.org/
[link_name] => Snorby - Snort front-end
[link_notes] =>
[added_date] => 2011-05-03
[flag_new] => 1
[rating] => 4
[public] => 1
)
)
[2] => Array
(
[0] => stdClass Object
(
[user_id] => 2
[link_id] => 1176
[link_url] => http://www.nytimes.com/2011/04/17/business/17excerpt.html?_r=4&pagewanted=1&ref=business
[link_name] => Corner Office - The 5 Habits of Highly Effective C.E.O.s
[link_notes] => Sounds a lot like what Nathanial said...
[added_date] => 2011-04-21
[flag_new] => 1
[rating] => 4
[public] => 1
)
)
[3] => Array
(
[0] => stdClass Object
(
[user_id] => 2
[link_id] => 1175
[link_url] => http://chezlarsson.com/myblog/2010/06/panduro-concrete-challenge-3.html
[link_name] => Concrete book-ends
[link_notes] => Cool look...
[added_date] => 2011-04-10
[flag_new] => 1
[rating] => 4
[public] => 1
)
[1] => stdClass Object
(
[user_id] => 2
[link_id] => 1174
[link_url] => http://themeforest.net/item/reciprocity-photo-blog-gallery/154590
[link_name] => Site Templates - Reciprocity - Photo Blog
[link_notes] =>
[added_date] => 2011-04-10
[flag_new] => 1
[rating] => 5
[public] => 1
)
)
[4] => Array
(
[0] => stdClass Object
(
[user_id] => 2
[link_id] => 1173
[link_url] => http://lifehacker.com/#!5771943/the-always-up+to+date-guide-to-jailbreaking-your-ios-device
[link_name] => The Always Up-to-Date Guide to Jailbreaking Your iOS Device
[link_notes] =>
[added_date] => 2011-03-04
[flag_new] => 1
[rating] => 4
[public] => 1
)
)
[5] => Array
(
[0] => stdClass Object
(
[user_id] => 2
[link_id] => 1172
[link_url] => http://lifehacker.com/#!5754463/how-to-jailbreak-your-ios-421-device
[link_name] => How to Jailbreak Your iOS 4.2.1 Device
[link_notes] =>
[added_date] => 2011-02-28
[flag_new] => 1
[rating] => 4
[public] => 1
)
)
[6] => Array
(
[0] => stdClass Object
(
[user_id] => 2
[link_id] => 1171
[link_url] => http://www.bitplumber.net/2010/10/a-cassandra-hardware-stack-dell-c1100s-ocz-vertex-2-ssds-with-sandforce-arista-7048s/
[link_name] => A Cassandra Hardware Stack
[link_notes] =>
[added_date] => 2011-02-22
[flag_new] => 1
[rating] => 3
[public] => 1
)
)
)
... all seems fine enough. But my problem comes from my view, where I'm trying to build the HTML as described above. A simplified view of the code I'm trying to get to work is as follows:
foreach ($link_headers as $header) {
echo "INDEX: ". $links_headers .", ADDED DATE: ". $header->added_date ."<BR>";
foreach ($links_result[$link_headers] as $result){
echo $result->added_date ."<BR>";
echo $result->link_name ."<BR><BR>";
}
}
So, I'm trying to use the index of the first one to tell my foreach loop which index of the second array to loop through and get the content. Clearly I'm misusing the $links_result[$link_headers] variable(s) but I left it in to show what I was trying to do.
Any help is very much appreciated!
Michael
I dont use CodeIgniter but whether within th framework or from PHP i would just grab it all in one go and then the issue with the indexes becomes moot:
SELECT * FROM model_table mt WHERE mt.added_date IN (
SELECT DISTINCT md.added_date from model_table md
ORDER BY md.added_date DESC
LIMIT 7
) ORDER BY mt.added_date DESC
That should get you an array of models ordered by date limted to the 7 most recent dates. So then its just a matter of choosing when to display a header:
$current = null;
foreach($links as $link) {
if($link->added_date !== $current) {
// show the header and set current to the current date
$current = $link->added_date;
echo 'HEADER: Added on ' . $current . '<br />';
}
echo $row->added_date ."<BR>";
echo $row->link_name ."<BR><BR>";
}

getting story tags from graph api returns strange id results for the tagged

The best way for me to explain this is to show you. Seems like a float() error in a 64bit system.
when i call /anotherfeed/feed or any page for that matter, posts with story_tags return some of the id's as a float error.
sample story tag with float error in id. [id] => 1.7153566624E+14
My question is, how do i fix this, or what am i doing wrong? all i am doing is looping in a foreach statement.
if($fvalue[story_tags]){
echo 'Tags: ';
$sTags=$fvalue[story_tags];
foreach ($sTags as $skey=>$svalue){
foreach ($svalue as $gkey=>$hvalue){
$id=$hvalue[id];
echo ''.$hvalue[name].' '.$id.' ';
}
}
}
[story_tags] => Array
(
[0] => Array
(
[0] => Array
(
[id] => 1.7153566624E+14
[name] => Another Feed
[offset] => 0
[length] => 12
[type] => page
)
)
Array
(
[data] => Array
(
[0] => Array
(
[id] => 171535666239724_156133294510726
[from] => Array
(
[name] => Another Feed
[category] => App page
[id] => 171535666239724
)
[story] => Another Feed shared Non-Profits on Facebook's photo.
[story_tags] => Array
(
[0] => Array
(
[0] => Array
(
[id] => 1.7153566624E+14
[name] => Another Feed
[offset] => 0
[length] => 12
[type] => page
)
)
[20] => Array
(
[0] => Array
(
[id] => 41130665917
[name] => Non-Profits on Facebook
[offset] => 20
[length] => 23
[type] => page
)
)
)
[picture] => http://photos-d.ak.fbcdn.net/hphotos-ak-ash3/557037_10150932300320918_1908237167_s.jpg
[link] => http://www.facebook.com/photo.php?fbid=10150932300320918&set=a.85612830917.95996.41130665917&type=1
[name] => Wall Photos
[caption] => Have you heard of the #[159208207468539:274:One Day without Shoes] (ODWS) campaign? ODWS is an annual initiative by #[8416861761:274:TOMS] to bring awareness around the impact a pair of shoes can have on a child's life.
During the 2012 campaign, #[20531316728:274:Facebook] drove 20% of traffic to the ODWS microsite and TOMS even launched a Facebook-exclusive "Barefoot & Blue" giveaway with #[25266987484:274:Essie Nail Polish] for the second year in a row.
We think this is a pretty cool example of creating exclusive content around an important initiative that keeps people engaged and involved!
[properties] => Array
(
[0] => Array
(
[name] => By
[text] => Non-Profits on Facebook
[href] => http://www.facebook.com/nonprofits
)
)
[icon] => http://static.ak.fbcdn.net/rsrc.php/v2/yD/r/aS8ecmYRys0.gif
[type] => photo
[object_id] => 10150932300320918
[application] => Array
(
[name] => Photos
[id] => 2305272732
)
[created_time] => 2012-07-02T17:57:23+0000
[updated_time] => 2012-07-02T17:57:23+0000
[comments] => Array
(
[count] => 0
)
)
solution:
cURL - had to use number format with PHP_EOL to solve in cURL.
// $locs = curl call to graph api for /anotherfeed/feed, still need solution for foreach.
$locs=json_decode($returned, true);
$stId=number_format($locs[data][1][story_tags][0][0][id], 0, '', '').PHP_EOL;
echo $stId;
PHP-SDK
solution is same, long numbers in the foreach loop need to be ran through number_format.

Categories