Creating an object from an array of multiple values - php

I have this function:
function getPostInfo($query, $fields, $type, $limit, $since, $until, $lang, $stopwords, $identifier) {
$url = file_get_contents('https://graph.facebook.com/search?q='.spaces($query).'&fields='.$fields.'&limit='.$limit.'&until='.$until);
$j = json_decode($url);
foreach($j->data as $v) {
if ($v->type == $type) {
$author_id = $v->from->id;
$original_id = $v->id;
$post_url = getPostUrl($original_id, $author_id);
//$description = stopWords($v->message);
$description = $v->message;
$pub_date = $v->created_time;
$post[]= array(
'author_id' => $author_id,
'orginal_id' => $original_id,
'post_url' => $post_url,
'descritpion' => $description,
'pub_date' => $pub_date
);
}
}
return (object)$post;
}
If I call for example:
$post = getPostInfo($query, $fields, $type, $limit, $since, $until, $lang, $stopwords, $identifier);
echo $post->pub_date;`
it returns empty..
I tried to strip the [] from the $post array in the function...and in this case it returns only ONE value..
Instead it should return more values, because the object should get more values from the foreach loop in the above function..
But it's not happening..
I tried also to work with normal arrays, without an object, like this:
$post = getPostInfo($query, $fields, $type, $limit, $since, $until, $lang, $stopwords, $identifier);
echo $post['pub_date'];
In this case it always returns NULL..
What I am doing wrong?
How to assign more values to the array and getting them back when I need, knowing that the things I get should contain more values. It's like an array of an array...
I am a little confused..
I like the solution with objects, but if there is any other way, then better.
This is an example of what I get from the array $post:
array(5) { [0]=> array(5) { ["author_id"]=> string(10) "1319929690" ["orginal_id"]=> string(24) "1319929690_2736172406396" ["post_url"]=> string(77) "https://www.facebook.com/permalink.php?story_fbid=2736172406396&id=1319929690" ["descritpion"]=> string(773) "It was only a matter of time. # How do they serve alcoholic drinks on Italian cruise ships? - On the rocks # What vegetables do you get with dinner on Italian cruise ships? - Leeks # What's the fastest way to get off an Italian cruise ship? - Follow the captain # When the captain of the ill fated Costa Concordia was asked if he knew where he was going he replied "off course." # So the captain of the Costa Concordia will soon be in the dock. That's more than can be said for his ship. # The Costa Concordia is probably the most expensive thing to go down in Italy since Berlusconi's last hooker. # What's the difference between the Italian economy and the stricken cruise liner Costa Concordia? Nothing - The bottoms dropped out of both." ["pub_date"]=> string(24) "2012-02-04T14:36:54+0000" } [1]=> array(5) { ["author_id"]=> string(10) "1721122272" ["orginal_id"]=> string(24) "1721122272_1862454417365" ["post_url"]=> string(77) "https://www.facebook.com/permalink.php?story_fbid=1862454417365&id=1721122272" ["descritpion"]=> string(1968) "Thách thà ng nà o quánh tao 1. MỸ: “Tao muốn đánh thằng nà o, là tao đánh thằng đó. Ngoà i ra, tao bao tiá»n súng!†2. NATO: “Mỹ đánh thằng nà o, tao đánh thằng đó!â€. 3. NGA: “Thằng nà o bật tao, tao cắt dầu lá»­a!â€. 4. ISRAEL: “thằng nà o ngấm ngầm muốn đánh tao, tao đánh thằng đó!â€. 5. NHẬT: “thằng nà o đánh tao, tao sẽ bảo Mỹ đánh thằng đó. Nếu chúng mà y không ngừng tấn công, tao cho Maria Ozawa nghỉ việc!â€. 6. TRUNG QUá»C: “Thằng nà o gần tao, tao đánh thằng đó!â€. 7. ÄÀI LOAN: “Thằng nà o đòi đánh tao, tao bảo báo chí chá»­i thằng đó!â€. 8. NAM HÀN: “Thằng nà o định đánh tao, tao tập trận vá»›i thằng Mỹ!â€. 9. BẮC HÀN: “Thằng nà o là m tao bá»±c, tao sẽ đánh thằng Nam Hà n!â€. 10. Berlusconi (ITALIA): “Thằng nà o oánh tao, tao… ngủ vá»›i vợ thằng đó!â€. 11. SINGAPORE : “Thằng nà o đánh tao?!Chắc đếk thằng nà o rảnh mà đi đánh tao!â€. 12. IRAQ : “Thằng nà o đánh tao thì cứ đánh cho đã, chừng nà o mệt thì tá»± Ä‘á»™ng vá»!â€. 13. ARAP SAUDI : “Thằng nà o đánh tao, tao mua thằng đó!†14. Billaden: “Thằng nà o đánh tao, tao khủng bố thằng Mỹ!â€. 15. Liên Hiệp Quốc: “Tao dán cái mác… vùng cấm bay lên thằng nà o, chúng mà y úp sá»t thằng đấy cho tao!â€. 16. CUBA : “Thằng nà o oánh tao, tao cho Việt Nam má»™t mình canh giữ thế giá»›i!â€. 17. VIỆT NAM: “Chá»— nà o có oánh nhau, tao bà y tá» quan ngại sâu sắc. Còn thằng nà o oánh tao, tao tuyên bố chủ quyá»n, tao cắt Ä‘iện luân phiên, sau đó tao… cá»±c lá»±c lên án!â€. 18. THỤY SĨ : Thằng nà o đánh tao, Tao khóa tà i khoản tiá»n quốc gia thằng đó. 19. PHILIPIN : †Thằng nà o đánh tao, muốn hứng bão qua mà đánh. =]]" ["pub_date"]=> string(24) "2012-02-04T13:50:47+0000" } [2]=> array(5) { ["author_id"]=> string(9) "594958865" ["orginal_id"]=> string(27) "594958865_10150583915793866" ["post_url"]=> string(80) "https://www.facebook.com/permalink.php?story_fbid=10150583915793866&id=594958865" ["descritpion"]=> string(717) "# How do they serve alcoholic drinks on Italian cruise ships? - On the rocks # What vegetables do you get with dinner on Italian cruise ships? - Leeks # What's the fastest way to get off an Italian cruise ship? - Follow the captain # When the captain of the ill fated Costa Concordia was asked if he knew where he was going he replied "off course." # So the captain of the Costa Concordia will soon be in the dock. That's more than can be said for his ship. # The Costa Concordia is probably the most expensive thing to go down in Italy since Berlusconi's last hooker. # What's the difference between the Italian economy and the stricken cruise liner Costa Concordia? Nothing - The bottoms dropped out of both." ["pub_date"]=> string(24) "2012-02-04T13:15:45+0000" } [3]=> array(5) { ["author_id"]=> string(10) "1561522855" ["orginal_id"]=> string(24) "1561522855_2516825610916" ["post_url"]=> string(77) "https://www.facebook.com/permalink.php?story_fbid=2516825610916&id=1561522855" ["descritpion"]=> string(410) "Monti "frainteso" sulla monotonia del posto fisso??? Come Berlusconi che smentiva le proprie dichiarazioni mezzora dopo averle fatte??? Ma fatemi il piacere!!! La cosa che più mi fa specie é assistere all'atteggiamento di tanti antiberlusconiani di maniera che ieri si stracciavano le vesti per ogni cazzata che proveniva da Arcore e che oggi sono pronti a digerire politiche ed esternazioni anche peggiori!!" ["pub_date"]=> string(24) "2012-02-04T12:46:50+0000" } [4]=> array(5) { ["author_id"]=> string(9) "749211731" ["orginal_id"]=> string(27) "749211731_10150528401901732" ["post_url"]=> string(80) "https://www.facebook.com/permalink.php?story_fbid=10150528401901732&id=749211731" ["descritpion"]=> string(265) "B. al Financial Times: "Mi farò da parte dalla politica attiva e non ho nessuna intenzione di candidarmi ancora a primo ministro". Bossi: "Se Berlusconi si ritira è risolto il problema". La solida alleanza parlamentare che ha governato l'Italia in questi 20 anni." ["pub_date"]=> string(24) "2012-02-04T11:57:05+0000" } }

You need to call it out like this
echo $post[0]["author_id"];
echo $post[1]["author_id"];
You can also use a for each loop if you need to display all the values at once
foreach($post as $p){
echo $p["author_id"];
}

I'd stick to arrays personally, so return with return $post;
You would have to echo $post[0]['pub_date']; or $post[1]['pub_date']; or $post[2]['pub_date']; for the different rows.
Or you can loop
foreach ($post as $post_values){
echo $post_values['pub_date'];
}

Try doing somehting like this
$post[] = (object) array(
'author_id' => $author_id,
'orginal_id' => $original_id,
'post_url' => $post_url,
'description' => $description,
'pub_date' => $pub_date
);

Related

Arrays giving error when trying to echo

I have a huge array, in which i want to display the specific parts of it.
I have a part of it, here:
["dagskema"]=>
array(5) {
["Mandag (14/8)"]=>
array(2) {
["noter"]=>
array(1) {
[0]=>
string(30) "16:10-17:35 KOR i AVLSGÃ…RDEN"
}
["fag"]=>
array(8) {
[0]=>
array(2) {
["tekst"]=>
string(17) "2d re ​JH ​04"
["note"]=>
string(365) "14/8-2017 09:05 til 09:55 Hold: 2d re Lærer: Jens Christian von Holck (JH) Lokale: 04 Lektier: - Medbring en oplevelse fra sommerferien, hvor du på en eller anden måde har været i forbindelse/ vidne til/ tænkt over noget religiøst. Uddybning: Du skal kunne formidle din oplevelse via få stikord eller en enkelt kort sætning (skal kunne bruges anal [...]..."
}
[1]=>
array(2) {
["tekst"]=>
string(26) "2d SP ​BL ​01
intro"
["note"]=>
string(165) "intro 14/8-2017 10:05 til 10:55 Hold: 2d SP Lærer: Bjarke Ledskov (BL) Lokale: 01 Note: vi skal repetere materialet fra sidste år og snakke om hvad vi skal i år."
}
[2]=>
array(2) {
["tekst"]=>
string(17) "2d SP ​BL ​01"
["note"]=>
string(76) "14/8-2017 11:00 til 11:50 Hold: 2d SP Lærer: Bjarke Ledskov (BL) Lokale: 01"
}
[3]=>
array(2) {
["tekst"]=>
string(17) "2d Sa ​FS ​03"
["note"]=>
string(283) "14/8-2017 12:30 til 13:20 Hold: 2d Sa Lærer: Freja Schloss (FS) Lokale: 03 Lektier: - Terrorisme på tværs (Hansen & Jensen, side 26-32).pdf [...] Øvrigt indhold: - Rasmus Pöckel oprørsmodellen.docx [...] Note: Hvad er terrorisme? Hvordan kan vi præcist definere terrorisme?"
}
[4]=>
array(2) {
["tekst"]=>
string(17) "2d Sa ​FS ​03"
["note"]=>
string(359) "14/8-2017 13:25 til 14:15 Hold: 2d Sa Lærer: Freja Schloss (FS) Lokale: 03 Øvrigt indhold: - Why Russia’s reaction to the St. Petersburg bombing is all about strengthening Putin's power [...] (Eksempel på misbrug af ordet "terrorisme". Artikel fra Newsweek, 10. april 2017.) Note: Hvordan kan begreberne terror/terrorisme/terrorister misbruges?"
}
[5]=>
array(2) {
["tekst"]=>
string(17) "2d Ma ​Ma ​23"
["note"]=>
string(108) "Aflyst! 14/8-2017 14:20 til 15:10 Hold: 2d Ma Lærer: Malik Lindholdt (Ma) Lokale: 23 Note: Omsorgsdag (Ma)"
}
[6]=>
array(2) {
["tekst"]=>
string(17) "2d Ma ​Ma ​23"
["note"]=>
string(108) "Aflyst! 14/8-2017 15:15 til 16:05 Hold: 2d Ma Lærer: Malik Lindholdt (Ma) Lokale: 23 Note: Omsorgsdag (Ma)"
}
[7]=>
array(2) {
["tekst"]=>
string(108) "KOR i AVLSGÃ…RDEN
Alle 1. G. elever Alle 2. G. elever Alle 3. G. elever KOR 2017-18 ​LL ​AG1 (mu)"
["note"]=>
string(187) "Ændret! KOR i AVLSGÅRDEN 14/8-2017 16:10 til 17:35 Hold: Alle 1. G. elever, Alle 2. G. elever, Alle 3. G. elever, KOR 2017-18 Lærer: Svend Jørgen Lyngberg-Larsen (LL) Lokale: AG1 (mu)"
}
}
}
I specifically want's to target the "fag" array.
I tried the following, but it returns an error:
<?php
include("lectio/lectio.php");
$lectio = new lectio();
$skemamag = $lectio->get_skema_til_elev(94, 16305782848);
var_dump($skemamag);
?>
<div class="skema-lektioner-wrapper">
<?php foreach ($skemamag['dagskema']['Mandag (14/8)']['fag'][8] as $key => $val) {
echo '<p class="lektioner lektioner-'.$val.'">';
echo $val;
echo '</p>';
}?>
</div>
Error looks like this:
Warning: Invalid argument supplied for foreach() in /var/www/square-brain.com/itk/index.php on line 62
I use the api LectioAPI on github, link here
I specifically use this file
What am i doing wrong?
You need to look closer at you array structure. PHP is big on arrays, so you need to become familiar with them
<?php
foreach ($skemamag['dagskema']['Mandag (14/8)']['fag'] as $fag) {
// $fag is also an array, not sure if you want both of its members
// or just one
echo '<p>'
echo $fag['tekst'];
echo ' ';
echo $fag['note'];
echo '</p>';
}
?>
To avoid using the 'Mandag (14/8)' array by name, as it will probably change over time, you could do
<?php
foreach ($skemamag['dagskema'] as $d => $dag) {
echo echo "<p>$d</p>"; // echo that dag
foreach ( $dag['fag'] as $fag) {
echo '<p>'
echo $fag['tekst'];
echo ' ';
echo $fag['note'];
echo '</p>';
}
}
?>

Regex does not work in large string with html content [PHP]

I am trying to get values such R $ XX, XX [X is an example] using regular expression but I can not.
Below is my code:
$str = 'Indicada para 21 velocidades, corente indexadaCAPACETE MTB MANTUA MUSIC R$140,00PEDIVELA SHIMANO DEORE R$380,00PEDIVELA SHIMANO TX-71 R$99,00CORRENTE SHIMANO HG 40 R$55,00ROLO PARA TREINAMENTO TRANZ-X R$545,00CAPACETE MTB HIGH ONE (PROMOÇÃO) R$85,00BOMBA DE PÉ HIGH ONE COM MANÔMETRO (NYLON) R$89,90CAPA SELIM GEL (PRÓ-SPIN) R$45,00SUPORTE DE PAREDE VERTICAL R$20,00SUPORTE DE PAREDE HORIZONTAL R$35,00SUPORTE DE PAREDE VERTICAL PRETO R$28,00ESPUMA PARA GUIDÃO R$11,00BOMBA DE PÉ BETO NYLON R$55,00
Bomba pé nylon, acompanha adaptadores: valvula,bola e infláveisALAVANCA SHIMANO XT DUAL CONTROL EFM 761 R$500,00
Alavanca (par) 27 velocidades com manetes para freios mecânicos, com tecnologia "Dual Control" que chega muito próximo do sistema "STI" das bikes de corrida.
SAPATILHA SHIMANO MTB M 064 R$285,00
Pele sintética e malha flexível, resistentes ao esticar.
Entressola de poliamida reforçada com fibra de de vidro.
Pamilha estruturalmente flexível de acordo com uma ampla variedade de formatos de pé.
Volume + forma para melhor acomodação dos dedos dos pés.
Proteção em borracha oferece excelante tração e conforto para o caminhar.
Indicada para o pedal PD-M530, PD-M520.
Acompanha a base interna da sapatilha.ALAVANCA SHIMANO EF 51 R$130,00
Alavanca shimano 21 vel, ez-fire c/ maneteCAMPAINHA "I LOVE MY BIKE" R$14,00
Em alumínio, nas cores: polido, preto, azul e vermelho.
Fácil fixação no guidão.CAPACETE INFANTIL R$57,00CESTA ALUMÃNIO E NYLON
';
$regex = "/R\$[0-9]{1,},[0-9]{1,}/";
$result = preg_match_all($regex, $content, $rs);
var_dump($rs);
What's going on?
Try this code:
$content = "R$13,57 more text R$123,456";
$regex = "/$.*(R\$[0-9]{1,},[0-9]{1,}).*^/";
$result = preg_match_all($regex, $content, $rs);
var_dump($rs);
You need to place the group you are trying to match inside parentheses.

What could be causing this PHP page to work normally in WAMPServer, but not on a web server?

I made a HTML page in PHP to test a multilingual architecture and learn PHP.
A function in the file receives a language variable, paragraph number, sifts through a text file and returns the appropriate string.
I have been testing this locally and made sure it worked properly, but when I try this on my hosting service (making sure all paths and everything are unchanged), the script does not load and then a server error message appears.
I have also made sure that the version of PHP on my LAN and the version on the server match. (PHP Version 5.5.1.2).
What could be causing the program not to work?
The PHP file looks like this:
<!DOCTYPE html>
<html>
<head>
<title>PHP Test</title>
<link style rel=stylesheet href="style.css" type="text/css">
</head>
<?php
function skipLines($numberOfLanguages, $numberOfPairs, $openFile) {
//for the number of pairs given, skip numOfLangs * 2
//2 = one line for the numbers and one for the paragraph itself
for ($x=0; $x < (($numberOfPairs - 1) * $numberOfLanguages * 2); $x = $x + 1) {
//just casts them into the wind... like ashes
fgets($openFile);
}
}
function newRetriever($textPairNumber, $selectedLanguage, $openFile) {
//3 = numberOfLanguages
skipLines(3, $textPairNumber, $openFile);
$languageFound = false;
//test for language and return when true
while ($languageFound == false) {
//get the number and language in text after skipping is done
$currentPlaceArray = explode(" ", fgets($openFile));
$currentLanguage = $currentPlaceArray[1];
if (strcmp($currentLanguage, $selectedLanguage) == 2) {
$languageFound = true;
echo utf8_decode(fgets($openFile));
} else {
fgets($openFile);
}
}
//rewind
rewind($openFile);
}
?>
<body>
<h1>Human Rights Declaration</h1>
<p>This page uses PHP to retrieve different copies of text from each language and places them appropriately.</p>
<p>
<?php
$f = fopen("rawtext4languages.txt", "r");
newRetriever("3", "s", $f);
fclose($f);
?>
</p>
</body>
</html>
The text file has this basic format, divided by line breaks:
1 e
Line in English
1 s
Line in Spanish
1 f
Line in French
1 g
Line in German
2 e
Line in English
(...) And so forth
Also, you can see how it responds on the server here:
http://www.eamonbohan.com/Exercises/PHP/phplesson1.php
Additionally, I got an answer from my hosting service that says this:
Thank you for contacting our Help Desk. During the initial
investigation of your issue we noticed that your script is executing
in 30 seconds timeout. We increased the timeout for it to 120 seconds,
but it did not help. Here is the strace output of your script:
(Interjection: in the stack, there is an extra function I removed from the code above but it basically just builds a header based on the language variable. 0.000060 is the point in the strace output where things get weird).
eamonboh#eamonbohan.com [~/public_html/Exercises/PHP]# strace -s 2048 -r -p
`pgrep -u eamonboh php`
Process 29025 attached - interrupt to quit
0.000000 restart_syscall(<... resuming interrupted call ...>) = 0
4.021723 write(1, " <body>\n <h1>Human Rights Declaration</h1>\n <p>This page uses PHP to retrieve different copies of text from each language and places them appropriately.</p>\n <p>\n ", 182) = 182
0.000244 getcwd("/home/eamonboh/public_html/Exercises/PHP", 4096) = 41
0.000199 lstat("/home/eamonboh/public_html/Exercises/PHP/rawtexttrilingual.txt", {st_mode=S_IFREG|0644, st_size=3262, ...}) = 0
0.000359 open("/home/eamonboh/public_html/Exercises/PHP/rawtexttrilingual.txt", O_RDONLY) = 3
0.000125 fstat(3, {st_mode=S_IFREG|0644, st_size=3262, ...}) = 0
0.000163 lseek(3, 0, SEEK_CUR) = 0
0.000060 write(1, "<h2>", 4) = 4
0.000054 write(1, "1st", 3) = 3
0.000038 write(1, " ", 1) = 1
0.000134 write(1, "Spanis", 6) = 6
0.000038 write(1, "h article</h2>", 14) = 14
0.000060 read(3, "1 e\nAll human beings are born free and equal in dignity and rights. They are endowed with reason and conscience and should act towards one another in a spirit of brotherhood.\n1 s\nTodos los seres humanos nacen libres e iguales en dignidad y derechos y, dotados como est\303\241n de raz\303\263n y conciencia, deben comportarse fraternalmente los unos con los otros.\n1 f\nTous les \303\252tres humains naissent libres et \303\251gaux en dignit\303\251 et en droits. Ils sont dou\303\251s de raison et de conscience et doivent agir les uns envers les autres dans un esprit de fraternit\303\251.\n2 e\nEveryone is entitled to all the rights and freedoms set forth in this Declaration, without distinction of any kind, such as race, colour, sex, language, religion, political or other opinion, national or social origin, property, birth or other status.</p<p>Furthermore, no distinction shall be made on the basis of the political, jurisdictional or international status of the country or territory to which a person belongs, whether it be independent, trust, non-self-governing or under any other limitation of sovereignty.\n2 s\nToda persona tiene los derechos y libertades proclamados en esta Declaraci\303\263n, sin distinci\303\263n alguna de raza, color, sexo, idioma, religi\303\263n, opini\303\263n pol\303\255tica o de cualquier otra \303\255ndole, origen nacional o social, posici\303\263n econ\303\263mica, nacimiento o cualquier otra condici\303\263n.</p><p>Adem\303\241s, no se har\303\241 distinci\303\263n alguna fundada en la condici\303\263n pol\303\255tica, jur\303\255dica o internacional del pa\303\255s o territorio de cuya jurisdicci\303\263n dependa una persona, tanto si se trata de un pa\303\255s independiente, como de un territorio bajo administraci\303\263n fiduciaria, no aut\303\263nomo o sometido a cualquier otra limitaci\303\263n de soberan\303\255a.\n2 f\nChacun peut se pr\303\251valoir de tous les droits et de toutes les libert\303\251s proclam\303\251s dans la pr\303\251sente D\303\251claration, sans distinction aucune, notamment de race, de couleur, de sexe, de langue, de religion, d'opinion politique ou de toute autre opinion, d'origine nationale ou sociale, de fortune, de naissance ou de toute autre situation.</p><p>D"..., 8192) = 3262
0.000269 read(3, "", 8192) = 0
120.032177 --- SIGPROF (Profiling timer expired) # 0 (0) ---
0.000170 setitimer(ITIMER_PROF, {it_interval={0, 0}, it_value={120, 0}}, NULL) = 0
0.000134 rt_sigaction(SIGPROF, {0x810d70, [PROF], SA_RESTORER|SA_RESTART, 0x7f3369d02030}, {0x810d70, [PROF], SA_RESTORER|SA_RESTART, 0x7f3369d02030}, 8) = 0
0.000149 rt_sigprocmask(SIG_UNBLOCK, [PROF], NULL, 8) = 0
0.000078 open("php_errorlog", O_WRONLY|O_CREAT|O_APPEND, 0644) = 4
0.000224 write(4, "[12-Mar-2015 15:28:34 America/Chicago] PHP Fatal error: Maximum execution time of 120 seconds exceeded in /home/eamonboh/public_html/Exercises/PHP/phplesson1.php on line 56\n", 174) = 174
0.000102 close(4) = 0
0.000076 write(1, "<br />\n<b>Fatal error</b>: Maximum execution time of 120 seconds exceeded in <b>/home/eamonboh/public_html/Exercises/PHP/phplesson1.php</b> on line <b>56</b><br />\n", 165) = 165
0.000072 chdir("/home/eamonboh/public_html/Exercises/PHP") = 0
0.000048 setitimer(ITIMER_PROF, {it_interval={0, 0}, it_value={0, 0}}, NULL) = 0
0.000088 close(3) = 0
0.000277 --- SIGTERM (Terminated) # 0 (0) ---
Any advice would be greatly appreciated by this webdev newbie.

read file in descending php [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 11 years ago.
hi im trying to read a file in descending order.
i want to echo last 10 words from the file
expected result:
brian tracy, brian tracy, der reiche
sack, der reiche sack, der reiche
sack, electrical machines by charles s
siskind second e, test de politica
fiscal, gigantomastia,gigantomastia,,
a,
file i want to read :
find a doctor, Find a Doctor,technique with fingers of right hand over left ven, la empresa adaptable, la empresa adaptable en la era de la informaci n, la pobre mia, probabilidad estadistica, crack beam, dwarf rabbit, probabilidad estadistica, kamsutra bangla, power of the dog, power of the dog, prinsip kerja uji ninhidrin, letramania 3, gre, gre, prinsip kerja uji ninhidrin, prinsip kerja uji ninhidrin, artificial intelligence a modern approach, configuring sap erp financials and controlling, gas spring, imperio carolingio, blue collar man, caligrafia, wonderlic, women and weight loss tamasha, women and the weight loss tamasha, vivir amar y aprender leo buscaglia, vivir amar y aprender leo buscaglia, wonderlic, plan de manejo ambiental, calibra o de manometros, curso de carpinteria, secreto industrial, secreto industrial, deneme, elementos secundarios de un triangulo, imperio carolingio, caligrafia, construir en lo construido, plan de manejo ambiental, lisboa, lisboa secreta, modelo de contrato secreto industrial, el conde de montecristo, metode titrasi formol, metode titrasi formol, probabilidad estadistica, probabilidad estadistica, history of islam akbar shah najeebabadi, caligrafia, caligrafia, conversacion en la catedral, brian tracy, brian tracy, der reiche sack, der reiche sack, der reiche sack, electrical machines by charles s siskind second e, test de politica fiscal, gigantomastia,gigantomastia, Find a Doctor, Find a Doctor,technique with fingers of right hand over left ven, la empresa adaptable, la empresa adaptable en la era de la informaci n, la pobre mia, probabilidad estadistica, crack beam, dwarf rabbit, probabilidad estadistica, kamsutra bangla, power of the dog, power of the dog, prinsip kerja uji ninhidrin, letramania 3, gre, gre, prinsip kerja uji ninhidrin, prinsip kerja uji ninhidrin, artificial intelligence a modern approach, configuring sap erp financials and controlling, gas spring, imperio carolingio, blue collar man, caligrafia, wonderlic, women and weight loss tamasha, women and the weight loss tamasha, vivir amar y aprender leo buscaglia, vivir amar y aprender leo buscaglia, wonderlic, plan de manejo ambiental, calibra o de manometros, curso de carpinteria, secreto industrial, secreto industrial, deneme, elementos secundarios de un triangulo, imperio carolingio, caligrafia, construir en lo construido, plan de manejo ambiental, lisboa, lisboa secreta, modelo de contrato secreto industrial, el conde de montecristo, metode titrasi formol, metode titrasi formol, probabilidad estadistica, probabilidad estadistica, history of islam akbar shah najeebabadi, caligrafia, caligrafia, conversacion en la catedral, brian tracy, brian tracy, der reiche sack, der reiche sack, der reiche sack, electrical machines by charles s siskind second e, test de politica fiscal, gigantomastia,gigantomastia,, a,
If the file will not be too big, you can simply read it all and then remove the data you don't need :
$content = file_get_contents($filename); // $filename is the file to read
$chunks = explode($delimiter, $content); // $delimiter is your word separator
$chunks = array_slice($chunks, -$n); // $n is the number of words to keep from the end of the file
// NOTE : -$n !
If the file will grow beyond reasonable size to be loaded into memory, you may read it in chunks. Something like (untested) :
function getLastTokens($filename, $n, $delimiter) {
$offset = filesize($filename);
$chunksize = 4096; // 4K chunk
if ($offset <= $chunksize * 2) {
// our one liner here because the file is samll enough
$tokens = explode($delimiter, file_get_contents($filename));
} else {
$tokens = array();
$fp = fopen($filename, 'r');
$chunkLength = 0;
while (count($tokens) < $n && $offset > 0) {
$lastOffset = $offset;
$offset -= $chunksize;
if ($offset < 0) $offset = 0; // can't seek before first byte
$chunkLength += ($lastOffset - $offset); // how much to read
fseek($fp, $offset);
$data = fread($fp, $chunkLength); // read the next (previous) chunk
if (($pos = strpos($data, $delimiter)) !== false) {
$chunkLength = 0; // reset chunk size to read next time
$offset += $pos;
$data = explode($delimiter, substr($data, $pos + 1));
array_unshift($data, & $tokens); // make $tokens the $data array's first element
// with the last line, this is equivalent to
// array_push($tokens, $data[1], $data[2], $data[3], ....)
call_user_func_array('array_push', $data);
}
}
fclose($fp);
}
fclose($fp);
return array_slice($tokens, -$n);
}
$file = "File contents"; //File get contents or anything else here.
$array = explode(",", $file);
$array = array_slice($array, -10, 10); //Starting from Last 10th element, get Ten elements.
$string = implode(", ", $array);
echo $array;
Edit:
Changed the implementation to remove the loop and the count etc.
$text = file_get_contents($file); //get contents of file
$words = explode(',', $text); //split into array
if (($length = count($words) < 10) {
$lastWords = $words; //shorter than 10 so return all
} else {
for ($i = $length-11, $i < $length; $i++ { //loop through last 10 words
$lastWords[] = $words[$i]; //add to array
}
}
$str = implode(',', $lastWords); //change array back into a string
echo $str;

PHP array ordering

I was wondering how I could sort this array, when I use asort right now it does
14
17
16
15.
How would I go to have
14
15
16
17
array(4) {
[15]=> array(9) {
[2025]=> string(80) "20:25 à 21:15 Spectacle / L'histoire d'un coeur / Auditorium, É.S.P. De La Salle"
[2135]=> string(71) "21:35 à 22:25 Spectacle / Transfugue 2 / Auditorium, É.S.P. De La Salle"
[1430]=> string(64) "14:30 à 15:30 Mise en lecture/Théâtre la Catapulte / De La Salle"
[110]=> string(44) "11:00 à 13:00 Inscription / Pavillon Tabaret"
[1330]=> string(49) "13:30 à 14:30 CÉRÉMONIE D'OUVERTURE / De La Salle"
[1550]=> string(61) "15:50 à 16:40 Spectacle/Université Laurentienne / De La Salle"
[170]=> string(57) "17:00 à 17:50 Spectacle/Université d'Ottawa / De La Salle"
[1750]=> string(45) "17:50 à 19:00 REPAS DE L'AMITIÉ / De La Salle"
[1915]=> string(76) "19:15 à 20:05 Spectacle / Attendre la pluie / Auditorium, É.S.P. De La Salle" }
[16]=> array(8) {
[1845]=> string(81) "18:45 à 19:35 Spectacle / Mimes d'horreur / Salle Académique, Université d'Ottawa"
[1955]=> string(73) "19:55 à 20:45 Spectacle / Déroute / Salle Académique, Université d'Ottawa"
[8]=> string(45) "08:30 à 11:30 Atelier / ABC du jeu dramatique"
[13]=> string(41) "13:00 à 16:00 Atelier / Théâtre physique"
[1130]=> string(28) "11:30 à 13:00 DÎNER LIBRE / "
[1620]=> string(29) "16:20 à 18:20 SOUPER LIBRE / "
[220]=> string(58) "22:00 à 23:30 BAL MASQUÉ / l'Agora du centre universitaire"
[210]=> string(47) "21:00 à 22:00 Rétroaction / Université d'Ottawa" }
[17]=> array(4) {
[950]=> string(79) "09:50 à 10:40 Spectacle / Raison d'être / Salle Académique, Université d'Ottawa"
[110]=> string(76) "11:00 à 11:50 Spectacle / Potionnée / Salle Académique, Université d'Ottawa"
[120]=> string(28) "12:00 à 13:00 DÎNER LIBRE / "
[1330]=> string(48) "13:30 à 14:30 CÉRÉMONIE DE CLÔTURE / De La Salle" }
[14]=> array(1) {
[150]=> string(49) "15:00 à 16:30 Préparation technique / De La Salle" } }
You want ksort(), which will sort the array by key instead of value.
You're looking for the sort by key function:
ksort()
I would check out http://us.php.net/manual/en/function.sort.php. There are some examples there of how how to implement the sort the way you want. Also if its sorted but you want the reverse order use array_reverse().

Categories