I have 2 similar arrays:
$array_a = array(
array(
"id" => 1,
"merchant_reference" => "12345"
),
array(
"id" => 2,
"merchant_reference" => "67890"
)
);
$array_b = array(
array(
"id" => 1,
"merchant_reference" => "12345"
),
array(
"id" => 2,
"merchant_reference" => "67890"
),
array(
"id" => 3,
"merchant_reference" => "12345"
)
);
The only difference is $array_b has an additional item. I'd like to output a new array that counts the total keys of $array_a and removes all keys in $array_b up to that count. And, just leave the 3rd item in $array_b.
I've tried:
function compare_arrays($array1, $array2) {
$array1_count = count($array1);
$array2_count = count($array2);
$array2_count = $array2_count - $array1_count;
$array2 = array_slice($array2, $array1_count, $array2_count);
return $array2;
}
But, what's the best way to do this?
As per the discussion under comment, your code is fine, just an additional conditional check which will improve execution time in case no addition after 12 pm is found.
function compare_arrays($array1, $array2) {
$array1_count = count($array1);
$array2_count = count($array2);
$array2_count = $array2_count - $array1_count;
if($array2_count > 0){
return $array2 = array_slice($array2, $array1_count, $array2_count);
}
return $array1;
}
Here is my array prob with two values value (int) and tag (string).
At the end of loop I want to sort array by value and want to print top 5 values with their tag.
foreach($POS as $p)
{
//echo "POS :".$p."<br/>";
while ($row1 = #mysqli_fetch_array($selectTag))
{
//Calculate total pos for given tag
//echo "Tag : ".$row1['tag']."<br/>";
$selectPOS1 = mysqli_query($con,"SELECT * from koove_posts where tag = '".$row1['tag']."'");
while ($row2 = #mysqli_fetch_array($selectPOS1))
{
//echo $row2['pos']."<br/>";
$totalPOSs.=$row2['pos'].",";
}
$totalPOS_count = str_word_count($totalPOSs);
//calculate how many times particular 'pos' appears for given tag
$pos_Count = substr_count($totalPOSs, $p);
//Calculate the probability for each part of speach
$prob[] = (object) array(
"value" => ($pos_Count + 1)/ ($totalPOS_count + $distinct_pos_Count),
"tag" => $row1['tag'],
);
}
}
arsort($prob);
$prob = array_slice($prob, 0, 5);
foreach ($prob as $array)
{
echo "Tag :". $array->tag." Probablity :".$array->value."<br/>";
}
I tried this, but it prints first 5 tags from list.
You should use uasort function this way:
<?php
$prob = [];
$prob[] = (object) array('value' => 1, 'tag' => 2);
$prob[] = (object) array('value' => 2, 'tag' => 4);
$prob[] = (object) array('value' => 3, 'tag' => 6);
$prob[] = (object) array('value' => 4, 'tag' => 8);
$prob[] = (object) array('value' => 5, 'tag' => 10);
$prob[] = (object) array('value' => 6, 'tag' => 12);
var_dump($prob);
uasort ($prob, function($a, $b) {
if ($a->value == $b->value) {
return 0;
}
return ($a->value < $b->value) ? 1 : -1;
});
var_dump($prob);
I have an array like the following:
$content = array(array("id_post" => 1000, "id_user" => 4),
array("id_post" => 1001, "id_user" => 4),
array("id_post" => 1002, "id_user" => 3),
array("id_post" => 1003, "id_user" => 4),
array("id_post" => 1004, "id_user" => 5),
array("id_post" => 1005, "id_user" => 5));
So it means 5 => 1004, 1005 and 4 => 1000, 1001, 1003 and 3 => 1002.
First, how do I get this structure? (possible with commas)
My algorithm for this solution would be something like (here's what I'm asking you guys..how to accomplish this):
$arr = array();
for($i = 0; $i <= count($content) - 1; $i++){
if exists key ($content[$i]['id_user']) IN $arr then
$arr = add_to_existing_key "," . $content[$i]['id_post']
} other wise {
$arr = add_new_key PLUS value $content[$i]['id_user'] <=> $content[$i]['id_post']
}
}
I need the commas so I could parse the info later.
Basically, the objective of this is to do a loop with $arr variable. Imagining that the array would have, finally, something like:
("id_user" => 5, "ids" => '1004,1005'),
("id_user" => 4, "ids" => '1000,1001,1003'),
("id_user" => 3, "ids" => '1002')
for($i = 0; $i <= count($arr) - 1; $i++){
$ids = explode(",", $arr[$i]['ids']);
$info = array();
for($y = 0; $y <= count($ids) - 1; $y++){
$query->("SELECT * FROM table WHERE id = $ids[$y]");
$info[] = array($name, $description);
}
$email->sendEmail($info); // id = 5 => info OF 1004, 1005
$info = array(); // clear array
// loop
// id = 4 => info OF 1000, 1001, 1003
// loop etc
}
Try this:
$arr = array();
// Loop through each content
foreach ($content as $post)
{
$arr[$post['id_user']][] = $post['id_post'];
}
This way, the result would be
$arr = array(
'5'=> array('1004', '1005'),
'4'=> array('1000', '1001', '1003'),
'3'=> array('1002')
);
Then you won't need to use "explode" just to split those comma-separated IDs
Also
I think you might be better off sticking with arrays instead of joining on commas and then exploding later:
foreach($content as $values) {
if(!isset($result[$values['id_user']])) {
$result[$values['id_user']] = array();
}
array_push($result[$values['id_user']], $values['id_post']);
}
print_r($result);
May be this variant will be exactly what you need:
$content = array(array("id_post" => 1000, "id_user" => 4),
array("id_post" => 1002, "id_user" => 3),
array("id_post" => 1004, "id_user" => 5),
array("id_post" => 1003, "id_user" => 4),
array("id_post" => 1001, "id_user" => 4),
array("id_post" => 1005, "id_user" => 5));
// Make preparation array
foreach ( $content as $values ) {
if ( !isset($result[$values['id_user']]) ) {
$result[$values['id_user']] = array();
}
array_push($result[$values['id_user']], $values['id_post']);
}
// Sort inner arrays
foreach ( $result as $key => $valueArray ) {
asort($result[$key]);
}
// Implode arrays to strings
array_walk($result, function(&$array, $key) {
$array = implode(',', $array);
});
// Final array
$result1 = array();
foreach ( $result as $userID => $idsString ) {
$result1[] = array("id_user" => $userID, "id_post" => $idsString);
}
print_r($result1);
My function search inside a multi dimensional array for a match. It works but I would like to know if there is a better way to do that.
$arrays = array(
array('id' => 1, 'color_id' => 2, 'store_id' => 1),
array('id' => 1, 'color_id' => 2, 'store_id' => 2),
array('id' => 2, 'color_id' => 3, 'store_id' => 1)
);
function query_array($array, $keys = array(), $values = array()){
$match = array();
for($i = 0; $i < count($array); $i++){
for($x = 0; $x < count($keys); $x++){
if($array[$i][$keys[$x]] == $values[$x]){
$match[$i][] = 'increment';
if(count($match[$i]) == count($keys)){
return $array[$i];
}
}
}
}
return $match;
}
$searchKeys = array('item_id', 'store_id');
$searchValues = array(2,1);
$match = query_array($arrays, $searchKeys, $searchValues);
echo '<pre>';
print_r($match);
echo '<pre>';
I have an array like this:
array (0 =>
array (
'id' => '20110209172713',
'Date' => '2011-02-09',
'Weight' => '200',
),
1 =>
array (
'id' => '20110209172747',
'Date' => '2011-02-09',
'Weight' => '180',
),
2 =>
array (
'id' => '20110209172827',
'Date' => '2011-02-09',
'Weight' => '175',
),
3 =>
array (
'id' => '20110211204433',
'Date' => '2011-02-11',
'Weight' => '195',
),
)
I need to extract minimal and maximal Weight values.
In this example
$min_value = 175
$max_value = 200
Any help on how to do this ?
Thank you !
Option 1. First you map the array to get those numbers (and not the full details):
$numbers = array_column($array, 'weight')
Then you get the min and max:
$min = min($numbers);
$max = max($numbers);
Option 2. (Only if you don't have PHP 5.5 or better) The same as option 1, but to pluck the values, use array_map:
$numbers = array_map(function($details) {
return $details['Weight'];
}, $array);
Option 3.
Option 4. If you only need a min OR max, array_reduce() might be faster:
$min = array_reduce($array, function($min, $details) {
return min($min, $details['weight']);
}, PHP_INT_MAX);
This does more min()s, but they're very fast. The PHP_INT_MAX is to start with a high, and get lower and lower. You could do the same for $max, but you'd start at 0, or -PHP_INT_MAX.
foreach ($array as $k => $v) {
$tArray[$k] = $v['Weight'];
}
$min_value = min($tArray);
$max_value = max($tArray);
For the people using PHP 5.5+ this can be done a lot easier with array_column. Not need for those ugly array_maps anymore.
How to get a max value:
$highest_weight = max(array_column($details, 'Weight'));
How to get the min value
$lowest_weight = min(array_column($details, 'Weight'));
It is interesting to note that both the solutions above use extra storage in form of arrays (first one two of them and second one uses one array) and then you find min and max using "extra storage" array. While that may be acceptable in real programming world (who gives a two bit about "extra" storage?) it would have got you a "C" in programming 101.
The problem of finding min and max can easily be solved with just two extra memory slots
$first = intval($input[0]['Weight']);
$min = $first ;
$max = $first ;
foreach($input as $data) {
$weight = intval($data['Weight']);
if($weight <= $min ) {
$min = $weight ;
}
if($weight > $max ) {
$max = $weight ;
}
}
echo " min = $min and max = $max \n " ;
How about without using predefined functions like min or max ?
//find max
$arr = [4,5,6,1];
$val = $arr[0];
$n = count($arr);
for($i=0;$i<$n;$i++) {
if($val < $arr[$i]) {
$val = $arr[$i];
}
}
echo $val;
//find min
$arr = [4,5,6,1];
$val = $arr[0];
$n = count($arr);
for($i=0;$i<$n;$i++) {
if($val > $arr[$i]) {
$val = $arr[$i];
}
}
echo $val;
$num = array (0 => array ('id' => '20110209172713', 'Date' => '2011-02-09', 'Weight' => '200'),
1 => array ('id' => '20110209172747', 'Date' => '2011-02-09', 'Weight' => '180'),
2 => array ('id' => '20110209172827', 'Date' => '2011-02-09', 'Weight' => '175'),
3 => array ('id' => '20110211204433', 'Date' => '2011-02-11', 'Weight' => '195'));
foreach($num as $key => $val)
{
$weight[] = $val['Weight'];
}
echo max($weight);
echo min($weight);
<?php
$array = array (0 =>
array (
'id' => '20110209172713',
'Date' => '2011-02-09',
'Weight' => '200',
),
1 =>
array (
'id' => '20110209172747',
'Date' => '2011-02-09',
'Weight' => '180',
),
2 =>
array (
'id' => '20110209172827',
'Date' => '2011-02-09',
'Weight' => '175',
),
3 =>
array (
'id' => '20110211204433',
'Date' => '2011-02-11',
'Weight' => '195',
),
);
foreach ($array as $key => $value) {
$result[$key] = $value['Weight'];
}
$min = min($result);
$max = max($result);
echo " The array in Minnumum number :".$min."<br/>";
echo " The array in Maximum number :".$max."<br/>";
?>
$Location_Category_array = array(5,50,7,6,1,7,7,30,50,50,50,40,50,9,9,11,2,2,2,2,2,11,21,21,1,12,1,5);
asort($Location_Category_array);
$count=array_count_values($Location_Category_array);//Counts the values in the array, returns associatve array
print_r($count);
$maxsize = 0;
$maxvalue = 0;
foreach($count as $a=>$y){
echo "<br/>".$a."=".$y;
if($y>=$maxvalue){
$maxvalue = $y;
if($a>$maxsize){
$maxsize = $a;
}
}
}
echo "<br/>max = ".$maxsize;
print fast five maximum and minimum number from array without use of sorting array in php
:-
<?php
$array = explode(',',"78, 60, 62, 68, 71, 68, 73, 85, 66, 64, 76, 63, 81, 76, 73,
68, 72, 73, 75, 65, 74, 63, 67, 65, 64, 68, 73, 75, 79, 73");
$t=0;
$l=count($array);
foreach($array as $v)
{
$t += $v;
}
$avg= $t/$l;
echo "average Temperature is : ".$avg." ";
echo "<br>List of seven highest temperatsures :-";
$m[0]= max($array);
for($i=1; $i <7 ; $i++)
{
$m[$i]=max(array_diff($array,$m));
}
foreach ($m as $key => $value) {
echo " ".$value;
}
echo "<br> List of seven lowest temperatures : ";
$mi[0]= min($array);
for($i=1; $i <7 ; $i++)
{
$mi[$i]=min(array_diff($array,$mi));
}
foreach ($mi as $key => $value) {
echo " ".$value;
}
?>