Php sort by filename - php

I have this code
if($dateOrder){
$order = array(filemtime($filter_files[0]));
for($i=1;$i<$maxnr+1;$i++){
array_push($order,filemtime($filter_files[$i]));
}
array_multisort($order,SORT_DESC,SORT_NUMERIC,$filter_files,SORT_ASC,SORT_NUMERIC);
}
}
//end get image files
How to make possible sort order by filename? For example
picture1 , picture2 , picture3 picture10 , picture11

Here is the working code as per my proposal. The difference from your code is the usage of array_multisort method. PHP array_multiosrt expects single dimension non assoc arrays as its first and second dimension and then the whole data array as the last argument.
<?php
$dateOrder = true;
if($dateOrder){
/*$order = array(filemtime($filter_files[0]));
for($i=1; $i<$maxnr+1; $i++){
array_push($order,filemtime($filter_files[$i]));
}*/
$order = array('picture1', 'picture2', 'picture20', 'picture9', 'picture3', 'picture10', 'picture11');
//array_multisort($order,SORT_DESC,SORT_NUMERIC,$filter_files,SORT_ASC,SORT_NUMERIC);
$names = array();
for($i=0; $i<count($order); $i++) {
preg_match('/^(.+?)(\d+)$/', $order[$i], $matches);
$names[] = array($matches[1], $matches[2]);
}
$name = array();
$number = array();
foreach ($names as $key => $row) {
$name[$key] = $row[0];
$number[$key] = $row[1];
}
array_multisort($name, SORT_ASC, $number, SORT_NUMERIC, $names);
$output = array();
foreach ($names as $row) {
$output[] = $row[0] . $row[1];
}
print_r($output);
}
?>
Fiddle

Related

PHP Get duplicate values in array and average second value

I have an array that looks like this:
$ratingsInPosts = array
(
array("1",3),
array("2",5),
array("2",2),
array("5",2),
array("90",1),
array("5",6),
array("2",2),
);
I Want to find duplicate values in the first column and avarage its values from the second column.
So that this("1",3),("2",5),("2",2),("5",2),("90",1),("5",6),("2",2)
ends up like this ("1",3),("2",3),("5",4),("90",1)
Try this tested solution
I got the required Output
$ratingsInPosts = array
(
array("1",3),
array("2",5),
array("2",2),
array("5",2),
array("90",1),
array("5",6),
array("2",2),
);
$arr1 = array_column($ratingsInPosts, 0);
$p = array_count_values($arr1);
foreach($p as $key => $value)
{
$sum = 0;
for($i=0; $i < $value; $i++)
{
$pos = array_search($key, $arr1);
$sum += $ratingsInPosts[$pos][1];
unset($arr1[$pos]);
unset($ratingsInPosts[$pos]);
}
$re[] = array('"'.$key.'"',$sum/$value);
}
print_r($re);
I hope it helps you:
$groups = array();
// in this loop we group values by first column
foreach ($ratingsInPosts as $row) {
$key = $row[0];
if (!isset($groups[$key]) {
$groups[$key] = array();
}
$groups[$key][] = $row[1];
}
$result = array();
foreach ($groups as $key => $value) {
$avg = array_sum($value) / count($value);
$row = array($key, $avg);
$result[] = $row;
}
<?php
header('Content-Type: text/plain');
$ratingsInPosts = array(array("1",3),array("2",5),array("2",2),array("5",2),array("90",1),array("5",6),array("2",2));
$result = array();
$output = array();
foreach($ratingsInPosts as $array){
$result[$array[0]][] = $array[1];
}
foreach($result as $key=>$array){
$output[] = array($key,round(array_sum($array)/count($array)));
}
var_export($output);
?>

How to get specific values from an array in while loop

$array = array();
while ($row = mysqli_fetch_assoc($result)) {
$user_id = $row["user_id"];
$user_name = $row["user_name"];
}
foreach ($array as $arr) {
echo $arr;
}
Above code echos all the values from the $array how can I get a specific value of this array.
For example something like this echo $arr[2] (but it doesn't work)
Please mention that I'm getting some data from mysql and my purpose by asking this question is to get each value from a column separately.
Thank you if you can help me.
You forgot to fill your array with data...
while($row = mysqli_fetch_assoc($result)){
$array[]= array($row["user_id"], $row["user_name"]);
}
And now you can access to your data
foreach($array as $arr){
echo $arr[0];
echo $arr[1];
}
If you need to get the specific value of an array. you can get by
$array[2]
not
$arr[2]
Please try
$array = array();
while($row = mysqli_fetch_assoc($result)){
$array[] = $row;
}
foreach($array as $arr){
print_r($arr);
}
$array = array();
while($row = mysqli_fetch_assoc($result)){
$user_id = $row["user_id"];
$user_name = $row["user_name"];
$array[] = $row;
}
And use $array[2] to get records in 2nd index.
OR
foreach($array as $arr){
echo $arr[0];
echo $arr[1];
}
Also useful is to use the $key=>$value in your foreach loop.
foreach ($array as $key=>$value) {
echo $key."->".$value."<br />";
}
This will list each of your array items with values and respective keys.

how to convert index array to associative array?

I have an array like that
$products = array(array(354),array(1),array(375),array(1),array(344),array(2));
and i want to achieve array like that
$arrProducts= array(array('product_id'=>354,'qty'=>1),array('product_id'=>375,'qty'=>1),array('product_id'=>344,'qty'=>2));
I achieved this array using this code
foreach($products as $val)
{
$abc[] =$val[0];
}
for($i=0;$i<count($abc);$i++)
{
if($i%2==0)
{
$newarr[]['product_id'] = $abc[$i];
}
else{
$newarr[]['qty'] = $abc[$i];
}
}
for($j=0;$j<count($newarr);$j++)
{
if($j%2==0)
{
$arrProducts[] = array_merge($newarr[$j],$newarr[$j+1]);
}
else{
continue;
}
}
echo '<pre>';
print_r($arrProducts);
but i think my way to get this array is too long so how can i get this array in short way using some array functions or should i use this code?
You can use array_chunk in this case if this is always by twos, and combine it with array_combine():
$products = array(array(354),array(1),array(375),array(1),array(344),array(2));
$products = array_chunk($products, 2);
$arrProducts = array();
$keys = array('product_id', 'qty');
foreach($products as $val) {
$arrProducts[] = array_combine($keys, array(reset($val[0]), reset($val[1])));
}
echo '<pre>';
print_r($arrProducts);
Another alternative would be:
$products = array(array(354),array(1),array(375),array(1),array(344),array(2));
$keys = array('product_id', 'qty');
$arrProducts = array_map(function($e) use ($keys) {
return array_combine($keys, array_map('reset', $e));
}, array_chunk($products, 2));
This will yield the same result.
Consume two array elements on each iteration:
$arrProducts = array();
$inputLength = count($products);
for ($i = 0; $i < $inputLength; $i += 2) {
$arrProducts[] = array('product_id' => $products[$i][0], 'qty' => $products[$i+1][0]);
}
$i=1;
$j=0;
foreach($products as $val)
{
if(($i%2) == 0)
{
$abc[$j]['qty'] =$val[0];
$j++;
}
else
{
$abc[$j]['product_id'] =$val[0];
}
$i++;
}

how to store associative array php MySQL

I want to store result of a query as associative array. Below is my code that generates the query result below.
<?php
$include('config.php') //mysql connection file
$result = mysql_query("SELECT daystime.*, Sprinkler_ID FROM daystime, scheduler WHERE daystime.id = scheduler.DaysTime_ID ORDER BY daystime.id, Sprinkler_ID") or trigger_error(mysql_error());
$data_array = array();
while($rs = mysql_fetch_assoc($result))
{
$key=$rs['id'];
$value=$rs['Sprinkler_ID'];
$data_array[$key] = [$value];
}
foreach ($data_array as $key => $value)
{
echo $key.'=>'.$value.'<br />';
}
?>
This gives me output as
19=>Array
20=>Array
21=>Array
27=>Array
29=>Array
But I should get
19 -> [4,5],
20 -> [5],
21=>[4,6],
// and so on
$value is an array, you can't use echo on arrays
Don't loop just do a var_dump()
$data_array = array();
while($rs = mysql_fetch_assoc($result)){
$data_array[$rs['id']][]=$rs['Sprinkler_ID'];
}
var_dump($data_array);//or print_r($data_array);
<?php
$include('config.php') //mysql connection file
$result = mysql_query("SELECT daystime.*, Sprinkler_ID FROM daystime, scheduler WHERE daystime.id = scheduler.DaysTime_ID ORDER BY daystime.id, Sprinkler_ID") or trigger_error(mysql_error());
$data_array = array();
while($rs = mysql_fetch_assoc($result))
{
$key=$rs['id'];
$value=$rs['Sprinkler_ID'];
$data_array[$key] = [$value];
}
$out = '';
$count = count($data_array);
$iter = 0;
foreach ($data_array as $key => $value)
{
$out.= $key.'=>[';
foreach ($value as $val) {
$out.=$val.',';
}
$out = rtrim($out, ",");
$out.= ']';
if ($iter < ($count-1)) {
$out.=',<br />';
}
$iter++;
}
echo $out;
You need an inner foreach loop to handle printing the array in $value as this is a multi dimensional array. The preceding is an example of how it could look to produce the exact output you requested. If you are looking for a dump of the values, then please use the var_dump solution provided by #meda.
There are two issues in your code. The first is that $value is an array, the second is that this array only contains one item.
Try this:
$data_array = array();
while($rs = mysql_fetch_assoc($result))
{
$key=$rs['id'];
$value=$rs['Sprinkler_ID'];
$data_array[$key][] = $value;
}
foreach ($data_array as $key => $values)
{
echo $key.'=> [';
foreach($values as $value)
echo $value . ',';
echo ']<br />';
}

Array Exploding and matching per line / Using table Row

Hello can u give me the right code for this one...
$split_getCreatedfield = explode(",", "3,1,2");
$fieldsWithValue = explode("~","1->Samuel Pulta~2->21~3->Male~");
for($row=0;$row<count(fieldsWithValue);$row++){
$data = explode("->", $fieldsWithValue[$row]);
}
I want the output like this one
3 = 3 = Male
2 = 2 = 21
1 = 1 = Samuel Pulta
<?php
$split_getCreatedfield = explode(",", "3,1,2");
$fieldsWithValue = explode("~","1->Samuel Pulta~2->21~3->Male~");
$result = array();
foreach($fieldsWithValue as $key => $val){
if(trim($val) != ""){
$res = explode("->",$val);
$res_key = array_search($res[0],$split_getCreatedfield);
$result[$key][] = $split_getCreatedfield[$res_key];
$result[$key][] = $res[0];
$result[$key][] = $res[1];
}
}
krsort($result); /// Not really required
echo "<table>";
foreach($result as $vals){
echo "<tr><td>".$vals[0]."</td><td>=".$vals[1]."</td><td>=".$vals[2]."</td></tr>";
}
echo "</table>";
?>
output:
3 =3 =Male
2 =2 =21
1 =1 =Samuel Pulta
I would rather use preg_match_all(), like this:
$i = '3,2,1';
$s = '1->Samuel Pulta~2->21~3->Male~';
preg_match_all('/(\d+)->(.*?)(?:~|$)/', $s, $matches);
$fields = array_combine($matches[1], $matches[2]);
foreach (explode(',', $i) as $index) {
if (isset($fields[$index])) {
echo $index, ' = ', $index, ' = ', $fields[$index]. PHP_EOL;
}
}
The regular expression matches items like 1->Samuel Pulta and builds an array with the number as the key and whatever comes after it as the value.
Then, you simply iterate over the necessary indices and print their corresponding value from the $fields array.

Categories