how to sort 2d array php from sql inserted - php

This is my inseted sql to array
$e=0;
while ($row45 = mysqli_fetch_array($res1)) {
$proIdArr0["id"][$e]=$row45['proId'];
$proIdArr0["qty"][$e]=$row45["proQty"];
$e++;
}
print_r($proIdArr0);
And it prints
Array (
[id] => Array (
[0] => 15
[1] => 13
[2] => 16 )
[qty] => Array (
[0] => 54
[1] => 84
[2] => 54 )
)
and i want to sorted by the id so it will be for example this output
id | qty
-------
13 | 84
15 | 54
16 | 54

You can combine your array and then ksort it.
<?php
$array = [
"id" => [15,13,16],
"qty" => [54,84,54]
];
$combined = array_combine($array['id'], $array['qty']);
ksort($combined);
var_dump($combined);
Returns:
array(3) {
[13]=>
int(84)
[15]=>
int(54)
[16]=>
int(54)
}

Make id as the key and qty as value to sort on id , then some reverse enginering to get desired result.
<?php
$com = array_combine($proIdArr0["id"], $proIdArr0["qty"]);
ksort($com);
foreach($com as $k=>$v)
{
$proIdArr0["id"]=$k;
$proIdArr0["qty"]=$v;
}
But using order by in query is more preferable solution.

Related

How to count all values in a multidimensional array?

I have tried solutions to many similar questions, but they all seem to give me a count for each array. So I have the following array:
Array
(
[1] => Array
(
[0] => 1
[1] => 12
[2] => 2
)
[2] => Array
(
[0] => 1
[1] => 13
[2] => 3
)
[3] => Array
(
[0] => 1
[1] => 12
[2] => 2
)
[4] => Array
(
[0] => 1
)
[5] => Array
(
[0] => 1
)
)
I am trying to count the duplicates across all arrays. So the output should show:
Five 1's
Two 12's
One 13
Two 2's
At the moment I am trying:
foreach($data as $key => $row) {
print_r(array_count_values($row));
}
Which outputs the counts for each individual array
Array
(
[1] => 1
[12] => 1
[2] => 1
)
Array
(
[1] => 1
[13] => 1
[3] => 1
)
Array
(
[1] => 1
[12] => 1
[2] => 1
)
Array
(
[1] => 1
)
Array
(
[1] => 1
)
I have also tried this:
foreach ($data as $key => $row) {
$counts = array_count_values(array_column($data, $key));
var_dump($counts);
}
Which seems to miss a lot of information, like the count of the 1's
array(2) {
[12]=>
int(2)
[13]=>
int(1)
}
array(2) {
[2]=>
int(2)
[3]=>
int(1)
}
array(0) {
}
array(0) {
}
array(0) {
}
As a note, the initial array keys will not always be sequential, as this represents a row number. So this array may contain rows 1, 2, 5, 6, 7 etc.
How would I go about counting all duplicates together?
Since your array is not flattened, you will need to visit each value and increment unless you want to call merging functions.
Code: (Demo)
$array = [
1 => [1, 12, 2],
2 => [1, 13, 3],
3 => [1, 12, 2],
4 => [1],
5 => [1]
];
// make the generated value available outside of function scope
// \-------------------------------v--------------------------/
array_walk_recursive($array, function($v)use(&$output) { // visit each leafnode
if (isset($output[$v])) { // check if the key has occurred before
++$output[$v]; // increment
} else {
$output[$v] = 1; // declare as 1 on first occurrence
}
});
var_export($output);
Output:
array (
1 => 5,
12 => 2,
2 => 2,
13 => 1,
3 => 1,
)
Or, non-recursively:
foreach ($array as $row) {
foreach ($row as $v) {
if (isset($output[$v])) { // check if the key has occurred before
++$output[$v]; // increment
} else {
$output[$v] = 1; // declare as 1 on first occurrence
}
}
}
Or, a functional one-liner to flatten then count:
var_export(array_count_values(array_reduce($array, 'array_merge', array())));
Or, a functional one-liner with the splat operator to flatten then count:
var_export(array_count_values(array_merge(...$array)));
You can do this quite easily by using an accumulator array and iterating all the elements:
$result = [];
foreach ($data as $row) {
foreach($row as $value) {
$result[$value] = isset($result[$value]) ? $result[$value] + 1 : 1;
}
}
var_dump($result);
You can use call_user_func_array to merge all the individual arrays, and then array_count_values on that result:
$data = array
(array(1, 12, 2),
array(1, 13, 3),
array(1, 12, 2),
array(1),
array(1)
);
print_r(array_count_values(call_user_func_array('array_merge', $data)));
Output:
Array
(
[1] => 5
[12] => 2
[2] => 2
[13] => 1
[3] => 1
)

how to insert a array data in multiple columns based on a value pair which exists in array in php

array(1) {
[0]=> array(7) {
["ranking_course_id"]=> string(1) "2"
["ranking_college_id"]=> string(2) "20"
["ranking_year"]=> string(4) "2017"
["ranking_agency"]=> array(3) {
[0]=> string(1) "1"
[1]=> string(1) "2"
[2]=> string(1) "3"
}
["ranking_value"]=> array(3) {
[0]=> string(2) "10"
[1]=> string(2) "20"
[2]=> string(2) "30"
}
["ranking_salary"]=> string(9) "9.20 Lacs"
["ranking_fees"]=> string(6) "354500"
}
}
What I want to insert is the following.
course_id | college_id | ranking_agency | ranking | value | salary fees
2 20 1 10 9.20 354500
2 20 2 20 9.20 354500
2 20 3 30 9.20 354500
Please help me out.
Try this workout
$oldarray = array(array("ranking_course_id" => "2",
"ranking_college_id"=> "20",
"ranking_year"=> "2017",
"ranking_agency"=> array("1","2","3"),
"ranking_value"=> array("10","20","30"),
"ranking_salary"=> "9.20 Lacs",
"ranking_fees"=> "354500"));
for($i=0; $i<count($oldarray[0]['ranking_agency']); $i++)
{
$newarray[] = $oldarray[0];
$newarray[$i]['ranking_agency'] = $oldarray[0]['ranking_agency'][$i];
$newarray[$i]['ranking_value'] = $oldarray[0]['ranking_value'][$i];
}
echo "<pre>"; print_r($newarray);
echo "<pre>"; print_r($oldarray);
output:
newarray
Array
(
[0] => Array
(
[ranking_course_id] => 2
[ranking_college_id] => 20
[ranking_year] => 2017
[ranking_agency] => 1
[ranking_value] => 10
[ranking_salary] => 9.20 Lacs
[ranking_fees] => 354500
)
[1] => Array
(
[ranking_course_id] => 2
[ranking_college_id] => 20
[ranking_year] => 2017
[ranking_agency] => 2
[ranking_value] => 20
[ranking_salary] => 9.20 Lacs
[ranking_fees] => 354500
)
[2] => Array
(
[ranking_course_id] => 2
[ranking_college_id] => 20
[ranking_year] => 2017
[ranking_agency] => 3
[ranking_value] => 30
[ranking_salary] => 9.20 Lacs
[ranking_fees] => 354500
)
)
oldarray
Array
(
[0] => Array
(
[ranking_course_id] => 2
[ranking_college_id] => 20
[ranking_year] => 2017
[ranking_agency] => Array
(
[0] => 1
[1] => 2
[2] => 3
)
[ranking_value] => Array
(
[0] => 10
[1] => 20
[2] => 30
)
[ranking_salary] => 9.20 Lacs
[ranking_fees] => 354500
)
)
and now insert the records :)
This is altered version of #Nobita, for multidimensional array.
$oldarray = array(array("ranking_course_id" => "2",
"ranking_college_id"=> "20",
"ranking_year"=> "2017",
"ranking_agency"=> array("1","2","3"),
"ranking_value"=> array("10","20","30"),
"ranking_salary"=> "9.20 Lacs",
"ranking_fees"=> "354500"),
array("ranking_course_id" => "2",
"ranking_college_id"=> "20",
"ranking_year"=> "2017",
"ranking_agency"=> array("1","2","3"),
"ranking_value"=> array("10","20","30"),
"ranking_salary"=> "9.20 Lacs",
"ranking_fees"=> "354500"));
$new_array = [];
$j=0;//For row
foreach($oldarray as $array)
{
$i=0;//For ranking agency and ranking value
foreach ($array['ranking_agency'] as $key => $value) {
$new_array[$j] = $array;
$new_array[$j]['ranking_agency'] = $array['ranking_agency'][$i];
$new_array[$j]['ranking_value'] = $array['ranking_value'][$i];
$i++; $j++;
}
}
echo "<pre>";print_r($new_array);
exit;
The array generation based on the 'ranking_value' & 'ranking_agency'.
Happy coding...!
For inserting multiple records use the following code.
$this->db->insert_batch("table_name", $array_name);
For a single dimension array, use the following code.
$this->db->insert("table_name", $array_name);
For more details see Active Record Class.
array key should be same as them name of the column in that table you inserting

Enhancing asort by order of keys

I am using asort to sort the numeric array. For e.g.
$arr = [0,1,1,2,1,2,2,3];
After running asort I am getting:
Array
(
[0] => 0
[4] => 1
[2] => 1
[1] => 1
[6] => 2
[3] => 2
[5] => 2
[7] => 3
)
But I am expecting to get it in this order:
Array
(
[0] => 0
[1] => 1
[2] => 1
[4] => 1
[3] => 2
[5] => 2
[6] => 2
[7] => 3
)
See the difference in order of the keys above.
First sort the array.
Then generate an array by flipping in a way so that the keys can be separated according to values. Sort the arrays with keys and merge them to an array. And the combine the keys with the sorted values.
$arr = [0,1,1,2,1,2,2,3];
asort($arr);
$sorted = $arr;
$flipped = $new_keys = array();
foreach($arr as $key => $val) {
$flipped[$val][] = $key; // Get the keys
}
foreach($flipped as $key => $val_array) {
asort($val_array); // Sort the keys
$new_keys = array_merge($new_keys, $val_array);
}
$final = array_combine($new_keys, $sorted); // Combine them again
var_dump($final);
Output
array(8) {
[0]=>
int(0)
[1]=>
int(1)
[2]=>
int(1)
[4]=>
int(1)
[3]=>
int(2)
[5]=>
int(2)
[6]=>
int(2)
[7]=>
int(3)
}
This should work for you:
First walk through each array value with array_walk() and change each value to an array containing the value and the key.
After this use uasort() to sort your array and if both values are the same you use the key to choose which one should be first.
At the end just use array_column() to transform your array back.
<?php
$arr = [0,1,1,2,1,2,2,3];
array_walk($arr, function(&$v, $k){
$v = ["value" => $v, "key" => $k];
});
uasort($arr, function($a, $b){
if($a["value"] == $b["value"]) {
if($a["key"] == $b["key"])
return 0;
return $a["key"] > $b["key"] ? 1 : -1;
}
return $a["value"] > $b["value"] ? 1 : -1;
});
$arr = array_column($arr, "value", "key");
print_r($arr);
?>
output:
Array
(
[0] => 0
[1] => 1
[2] => 1
[4] => 1
[3] => 2
[5] => 2
[6] => 2
[7] => 3
)

Display array elements in a specific way

I am making a session based shopping cart system, and I need some help with displaying the array from the session. My array looks like this:
array(5) { [0]=> NULL [1]=> string(5) "TMRS1" [2]=> string(5) "TMRS2" [3]=> string(5) "TMRS1" [4]=> string(5) "TMRS3" }
I would like a script to count duplicate elements and display them.
For instance, TMRS1 would be set to $name1 (= TMRS1) and $quantity1 (= 2). The next item would then be $name2 and $quantity2 and so on.
Is this possible? You are more than welcome to post if you've got a better idea on how I can display the items in the cart. I just have to be able to pull some data from a database by using the name of the items, and then add up all the prices of the items :)
maybe you can use array_count_values()
example from php.net
<?php
$array = array(1, "hello", 1, "world", "hello");
print_r(array_count_values($array));
?>
The above example will output:
Array
(
[1] => 2
[hello] => 2
[world] => 1
)
With the array you give:
$shopping_cart = array("TMRS1","TMRS2","TMRS1","TMRS3");
$items_count = array_count_values($shopping_cart);
echo "Number of TMRS1 in the cart:".$item_count["TMRS1"];
This would leave you with an array with the data you need:
<?php
$tmrs = array(NULL, "TMRS1", "TMRS2", "TMRS1", "TMRS3");
foreach ($tmrs as $key => $val){
$duplicateArray[$key]['name'] = "TMRS" . $key; // only the name
$duplicateArray[$key]['quantity'] = (int) str_replace("TMRS", "", $val); // aquire only the value
}
print_r($duplicateArray);
?>
That would return:
Array
(
[0] => Array
(
[name] => TMRS0
[quantity] => 0
)
[1] => Array
(
[name] => TMRS1
[quantity] => 1
)
[2] => Array
(
[name] => TMRS2
[quantity] => 2
)
[3] => Array
(
[name] => TMRS3
[quantity] => 1
)
[4] => Array
(
[name] => TMRS4
[quantity] => 3
)
)
You could then output the name or the value like this:
<?php echo $duplicateArray[2]['name']; ?>

PHP How to calculate duplicate values in array

I would like to calculate duplicate values in my array by "groupid":
Example:
Array
(
[0] => Array
(
[id] => 1230
[groupid] => 177
[activity_group_last] => 1229
[name] => First name
)
[1] => Array
(
[id] => 1231
[groupid] => 177
[activity_group_last] => 1229
[name] => Second name
)
[2] => Array
(
[id] => 1232
[groupid] => 178
[activity_group_last] => 1229
[name] => Other name
)
)
Output array (2 groupid = 177 and 1 groupid = 178):
Array
(
[0] => Array
(
[id] => 1231
[groupid] => 177
[activity_group_last] => 1229
[name] => Second name
[count] => 2
)
[1] => Array
(
[id] => 1232
[groupid] => 178
[activity_group_last] => 1229
[name] => Other name
[count] => 1
)
)
Thanks!
If $value contains your array, then:
$count = array_count_values(array_map(function($item) {
return $item['groupid'];
}, $value));
var_dump($count);
$_tmp = $count;
$unique = array_filter($value, function(&$item) use (&$_tmp, $count) {
if (!--$_tmp[$item['groupid']]) {
$item['count'] = $count[$item['groupid']];
return true;
}
return false;
});
var_dump($unique);
results in:
array(2) {
[1]=>
array(5) {
["id"]=>
int(1231)
["groupid"]=>
int(177)
["activity_group_last"]=>
int(1229)
["name"]=>
string(11) "Second name"
["count"]=>
int(2)
}
[2]=>
array(5) {
["id"]=>
int(1232)
["groupid"]=>
int(178)
["activity_group_last"]=>
int(1229)
["name"]=>
string(10) "Other name"
["count"]=>
int(1)
}
}
You can also do this using an iterative function. If your input array is stored in $input and you want the results in $output:
function remove_duplicates($input_array) {
$output_array = array(); // Create an empty array for output
foreach($input_array as $input) { // Loop the input array
if(array_key_exists($input['groupid'], $output_array)) {
// We've already seen this groupid at least once
// Increment count
$input['count'] = $output_array[$input['groupid']]['count'] + 1;
} else {
// First time we've seen this groupid
// Set count to 1
$input['count'] = 1;
}
// Store data in $output_array, indexed by group_id
$output_array[$input['groupid']] = $input;
}
}
// This is your input array
$input = array(array('id'=>1230,'groupid'=>177,'activity_group_last'=>1229,'name'=>'First name'),
array('id'=>1231,'groupid'=>177,'activity_group_last'=>1229,'name'=>'Second name'),
array('id'=>1232,'groupid'=>178,'activity_group_last'=>1229,'name'=>'Other name'));
// This will set the output array correctly
$output = remove_duplicates($input);

Categories