/    Sign up×
Community /Pin to ProfileBookmark

Confused about sorting in PHP

I have a camera motion detect system i use for watching my cats, and it FTP’s all its images to a folder in my hosting. So I cobbled together this code from examples I found, to display all the images along with the filenames and timestamps. Unfortunately the camera software insists on creating subfolders for each camera and each day, so I had to use this RecursiveIteratorIterator class to gather and display all the images. In the below, you can see where I build up 3 arrays of all the filenames, timestamps, and fullpaths for display. It works but all the photos were completely out of order. How can I modify this so that all the files are displayed sorted by time stamps. I *think* I may need to create a new array of $indexes based on the $timestamps, and then in my display loop, use $indexes[$i] in place of just $i. But I’m not sure what sort function to use to do that.

<!DOCTYPE html>
<html>
<body>

<?php
$dir_path = “private/cats/”;
$extensions_array = array(‘jpg’,’png’,’jpeg’,’JPG’,’PNG’,’JPEG’);
$total = 0;

$objects = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($dir_path),

RecursiveIteratorIterator::LEAVES_ONLY);
foreach($objects as $filepath => $object)
{
$fileinfo = pathinfo($filepath);
// skip if no extension, or extension not in my allowed list
if (!isset($fileinfo[‘extension’])) continue;
if (!in_array($fileinfo[‘extension’], $extensions_array)) continue;

$timestamps[$total] = date(“F d Y H:i:s”, filemtime($filepath));
$filenames[$total] = $fileinfo[‘filename’] . “.” . $fileinfo[‘extension’];
$filepaths[$total] = $filepath;

$total++;

}

echo “<h1>$total Image Files</h1>”;
for ($i=0; $i < $total; $i++)
{
echo “<br><hr><h1>$filenames[$i] &nbsp;&nbsp; $timestamps[$i] <br></h1>”;
echo “<img src=’$filepaths[$i]’ style=’width:100%;height:auto;’><br>”;
}
?>

</body>
</html>

to post a comment
PHP

30 Comments(s)

Copy linkTweet thisAlerts:
@SempervivumNov 18.2018 — This can be done by putting all info into one associative array and sort it by use of usort and a callback function:
$dir_path = "images/";
$extensions_array = array('jpg','png','jpeg','JPG','PNG','JPEG');
$total = 0;
<br/>
<i> </i>$objects = new RecursiveIteratorIterator(
<i> </i>new RecursiveDirectoryIterator($dir_path),
<i> </i>
<i> </i>RecursiveIteratorIterator::LEAVES_ONLY);
<i> </i>$fi = [];
<i> </i>foreach($objects as $filepath =&gt; $object)
<i> </i>{
<i> </i> $fileinfo = pathinfo($filepath);
<i> </i> // skip if no extension, or extension not in my allowed list
<i> </i> if (!isset($fileinfo['extension'])) continue;
<i> </i> if (!in_array($fileinfo['extension'], $extensions_array)) continue;
<i> </i>
<i> </i> $fi[] = ["time" =&gt; filemtime($filepath),
<i> </i> "timestamp" =&gt;date("F d Y H:i:s", filemtime($filepath)),
<i> </i> "filename"=&gt;$fileinfo['filename'] . "." . $fileinfo['extension'],
<i> </i> "filepath" =&gt;$filepath];
<i> </i> $timestamps[$total] = date("F d Y H:i:s", filemtime($filepath));
<i> </i> $filenames[$total] = $fileinfo['filename'] . "." . $fileinfo['extension'];
<i> </i> $filepaths[$total] = $filepath;
<i> </i>
<i> </i> $total++;
<i> </i>}
<i> </i>var_dump($fi);
<i> </i>usort($fi, function($a, $b)
<i> </i>{
<i> </i> return ($a['time'] - $b['time']);
<i> </i>});
<i> </i>var_dump($fi);
Copy linkTweet thisAlerts:
@rootNov 18.2018 — What are you sorting and how do you want it sorted?

Then look on PHP.net and find the sort functions that are:

**[url=http://php.net/manual/en/function.arsort.php]arsort()[/url], [url=http://php.net/manual/en/function.asort.php]asort()[/url], [url=http://php.net/manual/en/function.ksort.php]ksort()[/url],[url=php.net/manual/en/function.rsort.php]rsort()[/url], [url=http://php.net/manual/en/function.sort.php]sort()[/url], [url=http//php.net/manual/en/function.uasort.php]uasort()[/url], [url=http://php.net/manual/en/function.uksort.php]uksort()[/url], [url=http://php.net/manual/en/function.usort.php]usort()[/url]**

There is a way to use the different array_* functions in conjunction with a callback that can be used to sort or process array elements without having to use a for loop or foreach loop.

example.
&lt;?php
function out($val, $key){
echo "$key = $valn";
}
$fruits = array("d" =&gt; "lemon", "a" =&gt; "orange", "b" =&gt; "banana", "c" =&gt; "apple");

echo "&lt;hr&gt;asort&lt;br&gt;";
asort($fruits);
array_walk($fruits,"out");

echo "&lt;hr&gt;arsort&lt;br&gt;";
arsort($fruits);
array_walk($fruits,"out");

echo "&lt;hr&gt;rsort&lt;br&gt;";
rsort($fruits);
array_walk($fruits,"out");

echo "&lt;hr&gt;sort&lt;br&gt;";
sort($fruits);
array_walk($fruits,"out");

echo "&lt;hr&gt;";
?&gt;
Copy linkTweet thisAlerts:
@PeterPan_321authorNov 19.2018 — Thanks guys. I have a LOT to learn about associative arrays, It didn't look like any of the sorting methods in the MANual would offer an easy fix, but that's probably because I'm just not understanding. In the meantime I came up with something that is probably an ugly kludge, but it works. In my original routine, in addition to building the three parallel arrays for the filenames, filepaths, and formatted time stamps, I added an array to hold the raw time (integer) stamps. So when that process completes, I do this... (please forgive my old school "c" mentality.)

$max = max($rawTimestamps);

$newtotal=0;


for ($i=0; $i < $total; $i++)

{

$lowest = min($rawTimestamps);

if ($lowest > $max) break; // stop when no more.

for ($j= 0; $j < $total; $j++)
{
if ($rawTimestamps[$j] != $lowest) continue;
$indexes[$newtotal++] = $j; // keep index. overwrite duplicates
$rawTimestamps[$j] = $max+1; // ensure never counted again.
}

}

So what i did here is I recorded the maximum value in my $rawtimestamps array and started a $newtotal variable. Then the outer loop records the lowest timestamp value in that array, while the inner loop looks for all occurrences of that timestamp, and adds the index location ($j) where they were found to a new array called $indexes. After each one is found it replaces the original integer timestamp with a value greater than the recorded max value. That prevents it from ever being discovered again as the "lowest' value. (It also makes it easy to break out of the outer loop, when the lowest value found on the last pass exceeds to original max value!).

OK, this process destroys the rawtimestamps array, but I won't ever need it again after this. The newly built up array called $indexes now serves as a map. When I next display all my files and photos, I just have one added step, to use this map value to index all my other file data...


echo "<h1>$newtotal Image Files</h1>";

for ($i=0; $i < $newtotal; $i++)

{

$ix= $indexes[$i]; // get index to progressively older files

echo "<br><hr><h1>$filenames[$ix] &nbsp;&nbsp; $timestamps[$ix] <br></h1>";

echo "<img src='$filepaths[$ix]' style='width:100%;height:auto;'><br>";

}

}

I am sure that my lack of understanding of associative arrays has made this code uglier than it needs to be. But it works, so now I have a working reference. I'll definitely try the associative array method @Sempervivum suggested and see how much faster (or slower) it is. Thanks again!

By the way, the editor in the new Webdeveloper.com doesn't seem to have a button to properly format code snippets, so I'm just pasting them in and hoping for the best. But is there a proper way (or some proper tags) to better format code for posts?
Copy linkTweet thisAlerts:
@rootNov 19.2018 — Still unsure of what you were wanting to achieve and surprised that the manual didn't provide any assistance.

There is nothing stopping you from switching between PHP and C if C gives you the exact mode of working for that process, as long as you can run the script or executable, PHP can call and run external scripts if permissions are set, I use a process where a CRONJOB calls a PHP script as I need some PHP processes before, like I have to call a bash script, when it completes execution hands control back to PHP with a file name, that file name is then pulled and data in it pushed in to the database in background, this then gets processed with another CRONJOB that runs 10 minutes after to process all data and ensure that enough time passes to process the data in the table.

Then... I would get a daily report in an email of that data in that table which was a constant and limited number along with a csv file to import in to my excel sheet.

I found that most web counters never gave me the data I wanted, so I agreed with my web host to have a portal to the server logs that my script with its signature they provided me with could trawl the logs for my data for my domain. I really suspect they liked my idea of the bash script to solve the problem.

The point.

With a bit of work, you can often get exactly what you want, it may not be pretty but that never matters, as long as you can read it and understand it, thats all that matters.

Good luck with it.
Copy linkTweet thisAlerts:
@PeterPan_321authorNov 20.2018 — @root#1597971 Much appreciated. What you said is new to me... working in C for web page actions. Probably because 90% of the time it needs to include an HTML form to offer some control, options, and defaults. All the examples I've seen of dealing with forms and server side processing always point me to PHP/Html combos. And while javascript has become plenty powerful too, the PHP variables are a reasonably safe way to have a basic password to, and compiled PHP seems to be very fast!

In the end, as I mentioned in my long winded post (LOL), I did come up with what I'd call a brute force solution. What I was looking for was, given an array of random timestamp integers, return another array whose elements contained indexes to progressively higher (or lower) elements in the first array. Kind of a re-mapping array. Thus, if i used that new mapping array to display consecutive photos in a loop, I could use the loop counter as an index to "look up" the next (older or younger) image index in the map, for display. I thought my double loop would be inefficient, But even testing with several hundreds of photos, the processing seemed instantaneous.

I just kept thinking there might be an existing sort routine to do what I did, and there probably is. But sometimes I waste a ton of time looking for some ready made class or function to simplify a task for me, and it the end it took less time to just "roll my own". My PHP coding often still does look like old school 'c', and aside from a few different rules, its basically the same, right?

I still wish I knew the proper way to post code on this board.
Copy linkTweet thisAlerts:
@cootheadNov 20.2018 — > @PeterPan_321#1598006

**[color=#069]

I still wish I knew the proper way to post code on this board.[/color]
**


This has been answered here...

[url=https://www.webdeveloper.com/forum/d/383022-how-do-i-display-code]**[color=#069]How do I display code[/color]**[/url]

_coothead_
Copy linkTweet thisAlerts:
@rootNov 20.2018 — Have you tried looking in to another way of sorting, like using a temporary SQL table that you simply sort then pull the results in order?
Copy linkTweet thisAlerts:
@PeterPan_321authorNov 20.2018 — @coothead#1598026 Thanks again! I was hoping to try it on my previous posts, but it looks like the system won't let me re-edit days after the fact.
Copy linkTweet thisAlerts:
@PeterPan_321authorNov 20.2018 — @root#1598030 No I haven't. I'm not lazy about learning, but I always have so many projects going that I end up learning new skills when I need them. I' ve barely scratched the surface in using SQL, and wouldn't know where to begin. But as long as I've solved the problem with 10 lines of code, I'm good with that. I think it also makes sense to solve problems the simplest way possible, wouldn't you agree? I mean, I know in the widows programming environment, I've seen coders pull in ExCell or create Acess databases just to do a few calculations (or in this case sorts). As I was working in the PHP environment, I'd have been willing to try existing PHP sort methods that accomplished what i wanted to do, and think i still can ONCE I master associative arrays. But I think pulling in databases services for such a small isolated task might be overkill for the time being. A good exercise for learning though!

Thanks again!
Copy linkTweet thisAlerts:
@rootNov 20.2018 — Search for how to create temporary result tables and joining results, intersections, that will be helpful to you.

There are a few things that can be done in SQL with the right construction of queries.
Copy linkTweet thisAlerts:
@SempervivumNov 20.2018 — ONCE I master associative arrays[/quote]It's highly recommendable to make yourself familiar with associative arrays at first. When dealing with a database later you will benefit from it as the syntax for dealing with result sets is similar or equal. When using PDO and a prepared statement, with named parameters these are handed over in an associative array.
Copy linkTweet thisAlerts:
@PeterPan_321authorNov 21.2018 — @Sempervivum#1598080

Would you be so kind as to give me an example, based on the problem I just solved via a different route? It will take some explaining so bear with me. I started with a two simple one dimensional arrays. One of filepaths to various image files, the other to unix time stamps for these same files. So a given index (let's say $i) could be used to look up the file path and timestamp.

Now, since I wanted to display the images in order of their ascending timestamps, I wrote the double loop I described earlier to create another simple array called $indexes, My "sort" routine progressively stored the index location to progressively older timestamps. So now, when I went to display the images, instead of just using a for() loop to progressively display the time stamps and images, I could take my index variable $i, and use it to "look up" the next index to be displayed in my "map" array...

$correctedIndex = $indexes($i);

So now, even though $i simply incremented from 0 to the total, my $correctedindex would ensure that the timestamp and image I pulled from the original arrays were in time-wise order.

So now, lets go back to that array i created with my sort routine. Again, it was a simple one dimensional array, filled with timestamps in random order. If I simply sorted that array, I would lose all the original index references I needed. But, maybe if if I had an associative array, where the integer timestamps were 'associated' with the filepath of each image, THEN if I sorted by the timestamps, I'd be able to do a "forEach" construct, and know that the timestamps and filepaths would be accessed in the order of the sort.

But all that is a concept in my head, and I've not been able to figure out how to implement it based on the online MANual for PHP associative arrays.
Copy linkTweet thisAlerts:
@SempervivumNov 21.2018 — If I simply sorted that array, I would lose all the original index references I needed.[/quote]PHP has many built in functions and it seems to me there is one that can do your task:

http://php.net/manual/en/function.array-multisort.php

As in this case I was not shure, if this function does what I expected it to do, I created a short snippet for testing:
$timestamps = [4000, 3000, 5000, 2000];
$filepaths = ["imga.jpg", "imgb.jpg", "imgc.jpg", "imgd.jpg"];
array_multisort($timestamps, $filepaths);
var_dump($timestamps);
var_dump($filepaths);
It verifies that this function performs kind of synchronized sorting of the two arrays.

Check if this function is applicable to your task and revert if it's not.
Copy linkTweet thisAlerts:
@rootNov 21.2018 — So the sort will be key based and not value based if you want the keys to be time stamps and have some value.

Your sort would be key based.

Copy linkTweet thisAlerts:
@PeterPan_321authorNov 21.2018 — Thanks @Sempervivum#1598105 ! That multi_sort() does seem to work! I had to embed it in html code to test and upload it to my hosting co, because I have nothing that can run PHP at home. But it worked as you described, and I tried the SORT_DESC flag too, and see that I can opt to sort in descending order. And, after adding other parallel arrays to the call, it continued to work! Well writing my own was still a good exercise, but I'll your your method.

@root#1598118 - I still don't quite understand keys yet, which is why I'd asked for an example of associative array. Maybe ALL arrays in PHP are associative in the background? I don't know,, but given I was starting by getting each image's fullpath into a $filepaths array, and storing each file's timestamps in a separate $timestamps array, From what you said, I get the feeling i could have placed both items in a single associative array, with the timestamps as keys, and then sorting the array by keys. But I'm not sure how I would have done that, because I still don't quite understand how keys work, or what the => operator actually means. I can keep trying, but an example would be appreciated. I realize its something I really need to learn, but I'm having trouble grasping how it works from the online MANual or other examples I've seen.
Copy linkTweet thisAlerts:
@NogDogNov 21.2018 — In some languages, you have arrays and hashes, where the "keys" in arrays are always integers (i.e. "indexes"), while hashes only have string keys. In PHP, there are only arrays, and they can use both string and integer keys interchangeably. Each of these is valid, though the "confusing_mess" is generally to be avoided (example in command line mode, thus those php &gt; prompts you wouldn't use in your PHP files):
[code=php]
14:25 $ php -a
Interactive shell

php > $my_array = array('one', 'two');
php > $my_array[] = 'threeeee';
php > var_export($my_array);
array (
0 => 'one',
1 => 'two',
2 => 'threeeee',
)
php > $my_array[2] = 'three';
php > var_export($my_array);
array (
0 => 'one',
1 => 'two',
2 => 'three',
)
php > $my_associative_array = array('first' => 'one', 'second' => 'two', 'third' => 'three');
php > var_export($my_associative_array);
array (
'first' => 'one',
'second' => 'two',
'third' => 'three',
)
php > $my_confusing_mess = array('one', 'second' => 'two', 'three');
php > var_export($my_confusing_mess);
array (
0 => 'one',
'second' => 'two',
1 => 'three',
)
php >
[/code]
Copy linkTweet thisAlerts:
@SempervivumNov 21.2018 —  I get the feeling i could have placed both items in a single associative array, with the timestamps as keys, and then sorting the array by keys. But I'm not sure how I would have done that, because I still don't quite understand how keys work, or what the => operator actually means.[/quote]You are right, you can use the unix time as a key as well. The code in my first posting needs minor modificatins to do so:<i>
</i> // filemtime is the key
// right to the equality sign is the value
// which is another array in this case
$fi[filemtime($filepath)] = [
// timestamp is the key
// date() is the value
"timestamp" =&gt;date("F d Y H:i:s", filemtime($filepath)),
"filename"=&gt;$fileinfo['filename'] . "." . $fileinfo['extension'],
"filepath" =&gt;$filepath
];
Doing it this way the array can be sorted easily without a callback funktion.
Copy linkTweet thisAlerts:
@PeterPan_321authorNov 21.2018 — @Sempervivum#1598126 Excellent! Must try this!

So if I understand the above correctly...

1) the raw unix file time integer is the first item in the $fi array, which becomes the key.

2) I can then add several more items and use => symbols to 'associate' the given name (like "filename") with each subsequent item

3) as long as the key (raw timestamp) is unique, I can continue adding additional files this way.

If that is correct, some more questions...

1) what would I do now to "sort" the whole associated array now, by those keys?

2) Can this type of array still be indexed? such as for($i =0; i < count($fi); $i++) { do stuff}?, and would the returned array elements now be in order of the sorted keys?

3) within the loop, I could then access my elements as $fi[$i] => "filename" ? and have them accessed in timestamp sorted order?

4) and finally, an unrelated but possibly troublesome question. Wouldn't using the timestamp as a key mean multiple files with the same timestamp would get overwritten? If so, I'm thinking it might be better if a simple increment number was used as the key ($number++), and then add the raw timestamp integer as an associated element. I could still sort based on the "timestamp" element I choose, right? I understand the order of identical timestamps is undefined in a sort, as long as files aren't lost in the process.
Copy linkTweet thisAlerts:
@SempervivumNov 21.2018 — Yes, you understood the first 1) ... 3) correctly.

Regarding the second list of questions:

1) As the key = timestamp is the value you intend to sort by, you have to sort by key, not by value, and use the function ksort():

http://php.net/manual/en/function.ksort.php

2) This array can be indexed, that means you can access an element by the timestamp if you know that it exists:
$thefi = $fi[$thetimestamp]However the keys of the array will not be continuous, therefore it is not possible to loop through this array by a simple for loop. You need to use foreach:
foreach($fi as $time=&gt;$data) {
echo $data['filename'] . ' taken at ' . $data['timestamp'];
}

3) Yes, when you use foreach this is possible, see code above.

4) Wouldn't using the timestamp as a key mean multiple files with the same timestamp would get overwritten?[/quote]Yes, this is true and this is one reason why I didn't choose this procedure in my first posting.
it might be better if a simple increment number was used as the key ($number++), and then add the raw timestamp integer as an associated element.[/quote]Now we are back at the code in my first posting: Incrementing the key can be done automatically by omitting the index when adding a record:
$fn[] =
And finally, as the sorting functions do not know about which element you intend to sort by you need to use a callback function:
usort($fi, function($a, $b)
{
return ($a['time'] - $b['time']);
});
Copy linkTweet thisAlerts:
@rootNov 22.2018 — > @PeterPan_321#1598121 [root](https://www.webdeveloper.com/forum/d/383007/15) - I still don't quite understand keys yet, which is why I'd asked for an example of associative array. Maybe ALL arrays in PHP are associative in the background? I don't know,, but given I was starting by getting each image's fullpath into a $filepaths array, and storing each file's timestamps in a separate $timestamps array, From what you said, I get the feeling i could have placed both items in a single associative array, with the timestamps as keys, and then sorting the array by keys. But I'm not sure how I would have done that, because I still don't quite understand how keys work, or what the => operator actually means. I can keep trying, but an example would be appreciated. I realize its something I really need to learn, but I'm having trouble grasping how it works from the online MANual or other examples I've seen.

http://php.net/manual/en/array.sorting.php

Yes time stamps as keys are just fine, however, consider what you have been taught in other lessons in school, like what is the rule for fractions? Yep... REDUCE TO ITS SIMPLEST FORM, so do likewise and use time() output to order your array keys by. That can then be used to get a String formatted date and time as you require after not during the recording process.

I still think that you are going to be better off using a database to push your data in to, produce sort data and queries from that much faster and easier than writing huge chunks of code.

Then theirs the memory aspect, how big is this data set going to be? If it is too big, your script may be terminated as will scripts that take too long to completes.

So SIMPLIFY your processes.
Copy linkTweet thisAlerts:
@PeterPan_321authorNov 23.2018 — Well I thank you all. I still have confusion and many unanswered questions, but I have a start and some good confirmations about the concepts of associative arrays.

One thing I still believe will be a flaw here. If I move to associative arrays for this little project and let timestamps be my keys, multiple images that have the same timestamp will be lost. Therefore, in addition to timestamps and filepaths I will have to add another item $count, that simply increments ($count++) and let that be the key since it will always be unique. So then I will have to figure out how to do my sort (or multisort) based on the key, but on on the 'timestamp' element rather than the key. Is that possible?


Copy linkTweet thisAlerts:
@SempervivumNov 23.2018 — but on on the 'timestamp' element rather than the key. Is that possible?[/quote]Yes, this is possible: If you do not intend to sort by key but by the element 'timestamp' inside the data you need to use usort() and a callback function as pointed out in my previous posting.
Copy linkTweet thisAlerts:
@rootNov 24.2018 — > @PeterPan_321#1598202 . If I move to associative arrays for this little project and let timestamps be my keys

Ireally don't think you fully understand arrays.

KEYS are the ASSOCIATIVE array element, NUMERIC arrays are in their own right an associative array as the array position = the key, the value of the element is that property associated with the key.

time() = 12345566789

So its NUMERIC compared to "2018-10-21T12:34:56.789"

of should I put it in a format that you might recognise...

$arrayData = array( 123456789 =&gt; "something happened",
123499876 =&gt; "something else happened",
123698789 =&gt; "and something else happened");


and the PHP time() function outputs an integer number that is UNIQUE!!!
Copy linkTweet thisAlerts:
@PeterPan_321authorNov 24.2018 — > @root#1598207 Ireally don't think you fully understand arrays.

Well I confess you're right. But to be fair I've used arrays all my life and have been coding for many years, and have a level of proficiency in other languages. Its the properties of PHP arrays that have me confused. Part of the problem is that everyone that does fully understand are not always the best teachers, and the MANual for this language, though a good reference, is not the best teacher for learning the language from the ground up.

>
> KEYS are the ASSOCIATIVE array element, NUMERIC arrays are in their own right an associative array as the array position = the key, the value of the element is that property associated with the key.
>
> time() = 12345566789


I don't understand that syntax. I would take that as a function named time() is being set equal to a number.

>
> So its NUMERIC compared to "2018-10-21T12:34:56.789"

I understand the difference between a number and a string. But ordinary arrays referenced by position rather than key could also be an array of strings or other any objects. I don't think you're inferring that an array containing strings MUST be associative. Are you saying that arrays referenced by position could also be referenced by association?
>
> of should I put it in a format that you might recognise...
>
> $arrayData = array( 123456789 => "something happened",

> 123499876 => "something else happened",

> 123698789 => "and something else happened");


I've seen that use of => for an associative array. So USING that syntax lets the compiler or interpreter know that you're intention is to use this array as an associative array?

Here's a yes/no question: can an associative array also be referenced by position? For the above, could array position 0 (or $arraydata[0] ) be used to reference the key 123456789 and the string "something happened? in a for() loop with positional indexes?

> and the PHP time() function outputs an integer number that is UNIQUE!!!

But how does that relate to my MY situation? I was dealing with the timestamps on files which only resolve to a second, so its possible for several files being continually uploaded to end up with identical timestamps. hence, I realized I could not use that timestamp as a key, because multiple files stored in the array using the same key reference would overwrite each other.

I'm beginning to understand, but few manuals these days (including the PHP MANual) is not written as well as the Kernighan and Ritchie C manual. What I need, really, is a good complete reference and teaching book like that. I can usually get enough from MANual and other examples via GOOGLE. But if I really want to master these concepts, such a complete reference would be better than bothering every forum member to be my teacher.
Copy linkTweet thisAlerts:
@rootNov 24.2018 — no. all arrays in all languages are the same. The way you set them up are all slightly different but the way they work is all the same.

DIM x$[4] // Basic
$x = array() // PHP
x = new Array() // JavaScript
x$[5] = 99;
$x[6] = "z";
x[4] = "a";

the example time() = 123456789 is an indication that the output is an intewger, you can not assign a value to a function, only pass it.

These are fundamentals of programming that you will know already so I do not understand how you are having a problem.

In SQL the PHP scripts that you access the result set from an SQL query are eithe or both indexed or associative arrays depending on your needs.

There are many things that use arrays to store data that is easily accessed, then you have OBJECTS that are Array like.

These Arrays and Objects exist in all languages, including C and other higher level languages.

As for my pointing out that it is best to use a number and you say strings, can be used but what is easier to sort? Think about it before answering.

Your use of time() to get the time stamp for a key is eaily stored as that value or as a string.
$x = time();
$myArrayEntry[ $x ] = "Something happened now"; // with time ref as a numeric
$myArrayEntry[ "{$x}" ] = "Something happened now"; // with time ref as a string


Has it clicked yet?
Copy linkTweet thisAlerts:
@SempervivumNov 24.2018 — Here's a yes/no question: can an associative array also be referenced by position? For the above, could array position 0 (or $arraydata[0] ) be used to reference the key 123456789 and the string "something happened? in a for() loop with positional indexes?[/quote]

The answer is definitely no. You need to use the original key to get the value:

echo $arrayData[123499876];

will output "something else happened",

echo $arrayData[0];

will result in an error as the key 0 doesn't exist.

As already stated, a for loop is not applicable for iterating through an array where keys are not continuous. You should use foreach instead.
Copy linkTweet thisAlerts:
@rootNov 25.2018 — @Sempervivum#1598226 this issue the guy has IMHO is one where a database table is the more appropriate method of sorting a large data set.
Copy linkTweet thisAlerts:
@PeterPan_321authorNov 26.2018 — @root#1598219 Well I appreciate your help, but I assure you all arrays in all languages are not the same. In C, for example, array elements are always accessed by positional index. The kind of associative arrays I'm learning about in PHP don't exist there. And even in object oriented C++, you can't have different array elements contain completely different data types without special tricks (like having an object definition for everything, including simple numbers), and that would be considered wasteful. There are other differences, but what I've been trying to learn is the principals of associative arrays in PHP. Anyway, yes, its starting to "click".

And as far as pushing a group of temporary files into a database just so it can sort for me, I'm not saying its not a workable approach. I would consider that a wasteful for my application too, but I WILL try it as an exercise when I begin learning the PHP interface to SQL. Thanks for the aids.

@Sempervivum#1598226 I didn't think associative arrays could be indexed by position, but just checking. This was one of my reasons for believing the use of file timestamps as keys to a temporary array of files was not a good choice for my particular application. Since multiple files being received could easily have the same times stamp, using them as keys would cause files to be missed.

The method I'm using now works well, so thanks again everyone.
Copy linkTweet thisAlerts:
@rootNov 26.2018 — Last time I used C was a while ago and I recall not having to go through the convoluted statements that C++ versions have today.

All arrays are made in pretty much the same way, you have a declaration, a way of allocating space, how the inner workings applies its storage method, linked lists, whatever. As long as the user can declare a variable and its type, the programming under the hood don't matter.

Copy linkTweet thisAlerts:
@ginerjmNov 28.2018 — All arrays have indices. Period. Some are simply numerical based upon the order that the individual elements were added to the array. Some are non-numerical but rather strings which PHP calls "associative". The data is assigned using some string value as the index instead of a numeric value (or default number). Once the array is built the items can be referenced using an index of the type use to build that array.

I fail to see what the difficulty is for someone who professes to have a background in arrays. I do note that PHP provides a wealth of functions designed to manage and process arrays that exceeds any other language that I have used in the last 40 years.

So - why don't you just ignore all the stuff you are worrying about and simply try using an array and THEN tell us what doesn't work for you? Choose the associative type when you have meaningful entries that you would like to add to an array and default to a numeric array when you don't care about labels so much but rather handling a group of like data items that need to be gathered together and processed or sorted. PHP has some great array-sorting functions!
×

Success!

Help @PeterPan_321 spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 4.26,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,

tipper: @Samric24,
tipped: article
amount: 1000 SATS,
)...