PHP array ordering - php

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().

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.

At least one output file must be specified

I am using this command in ffmpeg
ffmpeg -i test.flv -i /var/www/phpvibe/logo.gif -filter_complex "scale=1200:-1,overlay=0:0" -s 1280x720 -vcodec libx264 -s 640x360 -movflags test.mp4 2>&1
But i am getting this
string(42) "At least one output file must be specified"
updated:-
php code:-
$output ='{ffmpeg-cmd} -i {input} -i /var/www/phpvibe/logo.gif -filter_complex "scale=1200:-1,overlay=0:0" -s 1280x720 -vcodec libx264 -s {ffmpeg-vsize} -threads 4 -movflags {output}.mp4 2>&1';
Complete output:-
array(33) {
[0]=>
string(83) "ffmpeg version git-2015-05-11-94c20de Copyright (c) 2000-2015 the FFmpeg developers"
[1]=>
string(51) " built with gcc 4.6 (Ubuntu/Linaro 4.6.3-1ubuntu5)"
[2]=>
string(243) " configuration: --enable-gpl --enable-libfaac --enable-libmp3lame --enable-libopencore-amrnb --enable-libopencore-amrwb --enable-librtmp --enable-libtheora --enable-libvorbis --enable-libvpx --enable-libx264 --enable-nonfree --enable-version3"
[3]=>
string(40) " libavutil 54. 23.101 / 54. 23.101"
[4]=>
string(40) " libavcodec 56. 38.100 / 56. 38.100"
[5]=>
string(40) " libavformat 56. 32.100 / 56. 32.100"
[6]=>
string(40) " libavdevice 56. 4.100 / 56. 4.100"
[7]=>
string(40) " libavfilter 5. 16.101 / 5. 16.101"
[8]=>
string(40) " libswscale 3. 1.101 / 3. 1.101"
[9]=>
string(40) " libswresample 1. 1.100 / 1. 1.100"
[10]=>
string(40) " libpostproc 53. 3.100 / 53. 3.100"
[11]=>
string(47) "Trailing options were found on the commandline."
[12]=>
string(31) "Input #0, flv, from 'test.flv':"
[13]=>
string(11) " Metadata:"
[14]=>
string(28) " audiosize : 150117"
[15]=>
string(26) " canSeekToEnd : true"
[16]=>
string(29) " datasize : 1015662"
[17]=>
string(26) " hasAudio : true"
[18]=>
string(27) " hasCuePoints : false"
[19]=>
string(26) " hasKeyframes : true"
[20]=>
string(26) " hasMetadata : true"
[21]=>
string(26) " hasVideo : true"
[22]=>
string(24) " lasttimestamp : 42"
[23]=>
string(72) " metadatacreator : flvtool++ (Facebook, Motion project, dweatherford)"
[24]=>
string(25) " totalframes : 229"
[25]=>
string(28) " videosize : 856032"
[26]=>
string(59) " Duration: 00:00:42.27, start: 0.066000, bitrate: 192 kb/s"
[27]=>
string(124) " Stream #0:0: Video: h264 (High), yuv420p, 176x144 [SAR 12:11 DAR 4:3], 165 kb/s, 30.30 fps, 29.97 tbr, 1k tbn, 59.94 tbc"
[28]=>
string(64) " Stream #0:1: Audio: aac (LC), 8000 Hz, stereo, fltp, 29 kb/s"
[29]=>
string(48) "Input #1, gif, from '/var/www/phpvibe/logo.gif':"
[30]=>
string(29) " Duration: N/A, bitrate: N/A"
[31]=>
string(67) " Stream #1:0: Video: gif, bgra, 90x55, 100 tbr, 100 tbn, 100 tbc"
[32]=>
string(42) "At least one output file must be specified"
}
int(1)
You put a -movflags without specifying a value before your output file. It thinks test.mp4 is the flag value hence your problem.

preg_match_all Specific REGEX

Could some one help me to formulate this REGEX because i am not familiar with preg_match_all filters, I want REGEX for :
sentence containing "petition" and delimited by . or a line break
Postal code have the format XXXXX (number) (with eventual space between the numbers ex : X XX XX or X XXXX )
$phone_regex = '~(?:\+?169|0)(?:\s*\d{3}){2}\s*\d{4}~';
$phone_res = preg_match_all($phone_regex, $content, $phone_matches);
REGEX 1
input :
1=> Plus de 5500 personnes ont déjà signé la pétition en ligne. Dans la droite ligne de ce mouvement, une manifestation est organisée jeudi devant la mairie de Metz.
2=> Dans un communiqué pétition
La décision de la Ville de Metz de confier les cinémas
output:
1=> Plus de 5500 personnes ont déjà signé la pétition en ligne.
2=> Dans un communiqué pétition
REGEX 2
input :
1=> 50040
2=> 50 040
3=> AA123
output :
1=> 50040
2=> 50 040
([^\.]*pétition[^\.^\n]*\.?)
And for your zip code : (\d\s?\d\s?\d\s?\d\s?\d)
Test this regex here with some sample texts before using it in your code : https://www.regex101.com/

Creating an object from an array of multiple values

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
);

Categories