Tracking elements of another array in foreach loop - php

I have two arrays, $files with file names and $imagesFormats with formats of this images. I want to move every file from $files to directory given in $imageFormats. Indexes of files and it's formats are same in both arrays. What's the best way to do this - creating another associative array ($image => $format) or there is another solution?

If the two array have the same key you can do in the same foreach .. eg:
foreach( $files as $key => $value ) {
yourfunction($value); ///
yourfunction($imagesFormats [$key] ) ;
}

Related

I want to move some elements of an array to array's top

I have an array: $content.
It's keys are only numbers.
I want to check whether a value is a valid directory. If it is, I want to move the value to the top of the array preserving the key, or in other words, move the entire key and value. Is this possible?
Here is the code:
foreach ($content as $item){
if(is_dir("path/$item")){
# the code for values movement should go here
}
}
You can achieve this by merging a temporary array into your $content array:
$temp = array($item => $content[$item]);
unset($content[$item]);
$content = $temp + $content;
You could split those arrays fist and then merge them again
So when it's a valid directory add to array1 and else add to array2

Build and fill multi-dimensional associative array from many delimited strings

I need to convert an structure like this:
$source[0]["path"]; //"production.options.authentication.type"
$source[0]["value"]; //"administrator"
$source[1]["path"]; //"production.options.authentication.user"
$source[1]["value"]; //"admin"
$source[2]["path"]; //"production.options.authentication.password"
$source[2]["value"]; //"1234"
$source[3]["path"]; //"production.options.url"
$source[3]["value"]; //"example.com"
$source[4]["path"]; //"production.adapter"
$source[4]["value"]; //"adap1"
into something like this:
$result["production"]["options"]["authentication"]["type"]; //"administrator"
$result["production"]["options"]["authentication"]["user"]; //"admin"
$result["production"]["options"]["authentication"]["password"]; //"1234"
$result["production"]["options"]["url"]; //"example.com"
$result["production"]["adapter"]; //"adap1"
I found a similar question but I can't adapt it to my particular version of the problem: PHP - Make multi-dimensional associative array from a delimited string
Not sure what problems you were running into, but the following works ok. See https://eval.in/636072 for a demo.
$result = [];
// Each item in $source represents a new value in the resulting array
foreach ($source as $item) {
$keys = explode('.', $item['path']);
// Initialise current target to the top level of the array at each step
$target = &$result;
// Loop over each piece of the key, drilling deeper into the final array
foreach ($keys as $key) {
$target = &$target[$key];
}
// When the keys are exhausted, assign the value to the target
$target = $item['value'];
}

Why is DirectoryIterator not going through all my files in php

can anyone tell me why my code is only outputting 20 out of 40 files
$Files = array();
$dir = new DirectoryIterator('./images/gallery');
foreach($dir as $fileinfo){
if($fileinfo->isFile()){
$Files[$fileinfo->getMTime()] = $fileinfo->getFilename();
}
}
krsort($Files);
foreach($Files as $file){
echo "<a rel='fancy1' href='/images/gallery/$file'><span><img src='/images/revelsmashy.php?src=/images/gallery/$file&w=128&zc=0&q=100'></span></a>\n";
}
edit:
i am looking to sort images based on the data time they were uploaded with the latest one posted 1st
Your original method of indexing the array by the file's modification time looks to be resulting in files having the same mtime values overwriting previous array keys. In some circumstances, if your whole directory were rewritten at once, all files could have the same modification time so only the last one iterated will be in the resultant array.
If you need to ultimately sort by the time, you can instead build a multidimensional array which holds both filenames and file modification times and then sort it using usort().
$dir = new DirectoryIterator('./images/gallery');
foreach($dir as $fileinfo){
if($fileinfo->isFile()){
// Append each file as an array with filename and filetime keys
$Files[] = array(
'filename' => $fileinfo->getFilename(),
'filetime' => $fileinfo->getMtime()
);
}
}
// Then perform a custom sort:
// (note: this method requires PHP 5.3. For PHP <5.3 the you have to use a named function instead.
// see the usort() docs for examples )
usort($Files, function($a, $b) {
if ($a['filetime'] == $b['filetime']) return 0;
return $a['filetime'] < $b['filetime'] ? -1 : 1;
});
In your output loop, access the filename key:
foreach($Files as $file){
echo "<a rel='fancy1' href='/images/gallery/{$file['filename']}'><span><img src='/images/revelsmashy.php?src=/images/gallery/{$file['filename']}&w=128&zc=0&q=100'></span></a>\n";
//-----------------------------------------^^^^^^^^^^^^^^^^^^^^
}

array_item[] = $file what does this do? [duplicate]

This question already has answers here:
What is the meaning of [] [closed]
(4 answers)
Closed 8 years ago.
I have been following a tutorial on readdir(), is_dir() etc involved in setting up a small image gallery based on folders and files on my FTP. I was wondering what the $directorys[] = $file; part does specifically?
while( $file= readdir( $dir_handle ) )
{
if( is_dir( $file ) ){
$directorys[] = $file;
}else{
$files[] = $file;
}
}
$directory is an array.
The code
$directory[] = $file
adds $file to the end of $directory array. This is the same as
array_push($directory, $file).
More info at array_push at phpdocs
$file will contain the name of the item that was scanned. In this case, the use of is_dir($file) allows you to check that $file in the current directory is a directory or not.
Then, using the standard array append operator [], the $file name or directory name is added to a $files/$directorys array...
It pushes an item to the array, instead of array_push, it would only push one item to the array.
Using array_push and $array[] = $item works the same, but it's not ideal to use array_push as it's suitable for pushing multiple items in the array.
Example:
Array (
)
After doing this $array[] = 'This works!'; or array_push($array, 'This works!') it will appear as this:
Array (
[0] => This works!
)
Also you can push arrays into an array, like so:
$array[] = array('item', 'item2');
Array (
[0] => Array (
[0] => item
[1] => item2
)
)
It adds the directory to the directory array :)
if( is_dir( $file ) ){
$directorys[] = $file; // current item is a directory so add it to the list of directories
}else{
$files[] = $file; // current item is a file so add it to the list of files
}
However if you use PHP 5 I really suggest using a DirectoryIterator.
BTW naming that $file is really bad, since it isn't always a file.
It creates a new array element at the end of the array and assigns a value to it.

how can i create array with foreach in php?

i am trying to create array like in the example i wrote above:
$arr=array('roi sabah'=>500,yossi levi=>300,dana=>700);
but i want to create it dynamic with foreach.
how can i do it ?
thanks.
You can access an array with foreach (and optionally create another one while going through the array's values). But if you only have data like a name and a number from your example, not stored in an array, you can't use foreach.
Another way to create the array you mentioned:
$arr = array();
$arr['roi sabah'] = 500;
$arr['yossi levi'] = 300;
// etc
And to access these values:
foreach ($arr as $key => $value) {
// $key is e.g. "roi sabah", and its value "500"
}

Categories