$arrayDif = array();
$arrayDif[] = array('employer' => $employer,
'comment' => $comment,
'value' => $resultValue);
Filling in from a loop.
Below is the array that I have filled up. I need to be able to find a match by the 'employer' and 'comment' and extract the value, so I can re-update this value.
Array
(
[0] => Array
(
[employer] => Albury-Wodonga
[comment] => allOtherMembers
[value] => 7
)
[1] => Array
(
[employer] => Albury-Wodonga
[comment] => associateMembers
[value] => 1
)
One command to extract and re-update the value, I suggest to use foreach loop
<?php
$arrayDif = array();
$arrayDif[] = array('employer' => "AAA", 'comment' => "comment 1", 'value' => "1");
$arrayDif[] = array('employer' => "BBB", 'comment' => "comment 2", 'value' => "2");
$arrayDif[] = array('employer' => "CCC", 'comment' => "comment 3", 'value' => "3");
// function for setting the value or returning the value
// notice the $array here is a reference to the real array
function func(&$array, $employer, $comment, $value = ''){
// $v is also a reference
foreach ($array as $k => &$v) {
if($v['employer'] == $employer && $v['comment'] == $comment) {
if(empty($value)) {
return $v['value'];
} else {
$v['value'] = $value;
}
}
}
return "Not Found.";
}
//update
func($arrayDif, 'AAA', 'comment 1', "123123");
//search
echo func($arrayDif, 'AAA', 'comment 1');
?>
Not sure if this is what you are looking for but here you go. I would use a function and simple loop.
<?php
$arrayDif = array();
$arrayDif[] = array(
array('employer' => "Albury-Wodonga", 'comment' => "allOtherMembers", 'value' => "1 star"),
array('employer' => "Employer2", 'comment' => "Good Job", 'value' => "2 stars"),
array('employer' => "Employer3", 'comment' => "Smart", 'value' => "3 stars")
);
// Function for searching the array for the matches and returning the value of the match.
function SearchMe($array, $searchEmployer, $searchComment){
for($i = 0; $i < count($array); $i++){
for($j = 0; $j < count($array[$i]); $j++){
if(
$array[$i][$j]["employer"] == $searchEmployer &&
$array[$i][$j]["comment"] == $searchComment
){
return $array[$i][$j]["value"];
}
}
}
return "No Match";
}
echo SearchMe($arrayDif, "Albury-Wodonga", "allOtherMembers");
?>
Related
I want to get most and least occuring values from php sequential/indexes, assoc and multidimensional arrays
Consider the following dataSet
$dataSet = [
'users' =>
[
'id' => 1,
'name' => "Alex",
'username' => 'alex',
],
[
'id' => 2,
'name' => "Alex",
'username' => 'alex'
],
[
'id' => 2,
'name' => "Peter Khot",
'username' => 'peter',
]
];
Here above are samples dataSet
Here is what that i tried
function most_occurring(array $array, $key)
{
$dataSet = [];
$i = 0;
$keys = [];
foreach ($array as $k) {
if (in_array($k[$key], $keys)) {
$keys[$i] = $k[$key];
$dataSet[$i] = $k;
}
$i++;
}
return $dataSet;
}
I tried above code for most occurring values but not working at all, help me in most and least occuring values from arrays.
Thanks
Thanks to KIKO Software, you can still use array_count_values() for this cases. You will also need to use array_columns() and array_search() in this situation. You can refer to this link to see how array_search() helps in finding the maximum/minimum value and its corresponding key inside an array. To find the most or least occurrence, simply echo the last 6 variables that I have declared in the last 6 lines.
EDIT* reference:
unset
array_push
*And also, your first data in the assoc array is indexed 'user', but the second data in the assoc array is not indexed and hence it is indexed as 0.
$dataSet = [
'users' =>
[
'id' => 1,
'name' => "Alex",
'username' => 'alex',
],
[
'id' => 2,
'name' => "Alex",
'username' => 'alex'
],
[
'id' => 2,
'name' => "Peter Khot",
'username' => 'peter',
]
];
$id = array_column($dataSet,'id');
$name = array_column($dataSet, 'name');
$username = array_column($dataSet, 'username');
$occur_id = array_count_values($id);
$occur_name = array_count_values($name);
$occur_username = array_count_values($username);
$most_occur_id = array_search(max($occur_id),$occur_id);
$most_occur_name = array_search(max($occur_name),$occur_name);
$most_occur_username = array_search(max($occur_username),$occur_username);
$least_occur_id = array_search(min($occur_id),$occur_id);
$least_occur_name = array_search(min($occur_name),$occur_name);
$least_occur_username = array_search(min($occur_username),$occur_username);
EDIT*: (In case of multiple highest occurence OR all same occurence, just add below code right below the above code.)
$flag = true;
$most_occur_name_list = [];
$count = 0;
while($flag)
{
$most_occur_name_ct = max($occur_name);
if($most_occur_name_ct == $count || $count == 0)
{
array_push($most_occur_name_list,array_search($most_occur_name_ct,$occur_name));
unset($occur_name[array_search($most_occur_name_ct,$occur_name)]);
$count = $most_occur_name_ct;
if(count($occur_name) == 0)
{
$flag = false;
break;
}
}
else
{
$most_occur_name_ct = $count;
$flag = false;
break;
}
}
//must reinitialize the array
$occur_name = array_count_values($name);
$flag = true;
$least_occur_name_list = [];
$count = 0;
while($flag)
{
$least_occur_name_ct = min($occur_name);
if($least_occur_name_ct == $count || $count == 0)
{
array_push($least_occur_name_list,array_search($least_occur_name_ct,$occur_name));
unset($occur_name[array_search($least_occur_name_ct,$occur_name)]);
$count = $least_occur_name_ct;
if(count($occur_name) == 0)
{
$flag = false;
break;
}
}
else
{
$least_occur_name_ct = $count;
$flag = false;
break;
}
}
if($most_occur_name_ct == $least_occur_name_ct)
{
$most_occur_name_list = [];
$least_occur_name_list = [];
}
echo "<pre>";
print_r($most_occur_name_list);
If you wanted to get a list of the min and max number of occurrences for just 1 element of the multidimensional array, then this code may offer a shorter method - comments in code...
$dataSet = [
'users' =>
[
'id' => 1,
'name' => "Alex",
'username' => 'alex',
],
[
'id' => 2,
'name' => "Alex",
'username' => 'alex'
],
[
'id' => 2,
'name' => "Peter Khot",
'username' => 'peter',
],
[
'id' => 2,
'name' => "Peter Khot",
'username' => 'peter',
],
[
'id' => 2,
'name' => "Paul Khot",
'username' => 'Paul',
]
];
// Create an array which has the username column, but retaining the keys from
// the original array
$set = array_combine(array_keys($dataSet),
array_column($dataSet, "username" ));
// Summarise the values
$count = array_count_values($set);
// Get a list of the keys which match the max and min values
$minRecords = array_keys($count,min($count));
$maxRecords = array_keys($count,max($count));
// Fetch the details for the maximum value (first one returned)
$maxElements = [];
foreach ( $maxRecords as $max ) {
$maxElements[] = $dataSet[array_search($max, $set )];
}
// Same for min values
$minElements = [];
foreach ( $minRecords as $min ) {
$minElements[] = $dataSet[array_search($min, $set )];
}
print_r($maxElements);
print_r($minElements);
With the test data I've added, you get the output...
Array
(
[0] => Array
(
[id] => 1
[name] => Alex
[username] => alex
)
[1] => Array
(
[id] => 2
[name] => Peter Khot
[username] => peter
)
)
Array
(
[0] => Array
(
[id] => 2
[name] => Paul Khot
[username] => Paul
)
)
My code to delete key like this :
<?php
$photoList = array(
array(
'id' => 1,
'name' => 'chelsea.jpg'
),
array(
'id' => 2,
'name' => 'mu.jpg'
),
array(
'id' => 3,
'name' => 'city.jpg'
)
);
if(count($photoList) > 1) {
$id = 1;
foreach($photoList as $key => $value) {
if($value['id'] == $id)
unset($photoList[$key]);
}
}
echo '<pre>';print_r($photoList);echo '</pre>';
?>
If the code executed, the result like this :
Array
(
[1] => Array
(
[id] => 2
[name] => mu.jpg
)
[2] => Array
(
[id] => 3
[name] => city.jpg
)
)
I want the value re-update. So id start from 1 and the key start from 0 like this :
Array
(
[0] => Array
(
[id] => 1
[name] => mu.jpg
)
[1] => Array
(
[id] => 2
[name] => city.jpg
)
)
How can I do it?
Please help me, what is wrong? thanks
You can keep a flag $delete and use that to remember if a delete has been done and then change the values if it's true.
if(count($photoList) > 1) {
$id = 1;
$delete = false;
foreach($photoList as $key => &$value) { // notice the & to make it by reference (editable)
if($value['id'] == $id && $delete == false){
$delete = true;
unset($photoList[$key]);
}Else if($delete == true){
$value["id"] = $id;
$id++; // update id for next value in array
}
}
}
$photoList= array_values($photoList);
https://3v4l.org/N2qjm
Without reference:
if(count($photoList) > 1) {
$id = 1;
$delete = false;
foreach($photoList as $key => $value) {
if($value['id'] == $id && $delete == false){
$delete = true;
unset($photoList[$key]);
}Else if($delete == true){
$photoList[$key]["id"] = $id;
$id++;
}
}
}
$photoList= array_values($photoList);
Try this..
<?php
$photoList = array(
array(
'id' => 1,
'name' => 'chelsea.jpg'
),
array(
'id' => 2,
'name' => 'mu.jpg'
),
array(
'id' => 3,
'name' => 'city.jpg'
)
);
$newphotolist = [];
$counter_id = 0;
if(count($photoList) > 1) {
$id = 1;
foreach($photoList as $key => $value) {
if($value['id'] != $id){
$counter_id++;
$arr = array('id' => $counter_id, 'name' => $value['name']);
$newphotolist[] = $arr;
}
}
}
echo '<pre>';print_r($newphotoList);echo '</pre>';
?>
$photoList = array(
array(
'id' => 1,
'name' => 'chelsea.jpg'
),
array(
'id' => 2,
'name' => 'mu.jpg'
),
array(
'id' => 3,
'name' => 'city.jpg'
)
);
if(count($photoList) > 1) {
$id = 1;
foreach($photoList as $key => $value) {
if($value['id'] == $id)
unset($photoList[$key]);
}
}
at the end of your job, reorder your key first.
$photoList = array_values($photolist);
and then, reorder your id.
foreach($photoList as $key=>$val) {
$photoList[$key]['id'] = $key+1;
}
<?php
$photoList = array(
array(
'id' => 1,
'name' => 'chelsea.jpg'
),
array(
'id' => 2,
'name' => 'mu.jpg'
),
array(
'id' => 3,
'name' => 'city.jpg'
)
);
if(count($photoList) > 1) {
$id = 1; $intStartId = 1;
foreach($photoList as $key => &$value) {
if($value['id'] == $id)
unset($photoList[$key]);
else {
$value['id'] = $intStartId;
++ $intStartId;
}
}
}
$photoList = array_merge(array(), $photoList);
echo '<pre>';print_r($photoList);echo '</pre>';
I've an array on php that will return a lot of keys->values, like this:
Array
[0] => Array
(
[value] => 405
[information] => some information1
)
[1] => Array
(
[value] => 500
[information] => some information2
)
[2] => Array
(
[value] => 700
[information] => some information3
)
the values are numbers, i need to collect all the values, check the first one that will be >= $determinedvalue and then return the value "information" for this exactly array, is this even possible? I know i can do this if i create a temp table on my database, but i dont want to.
To be more clearly, when my value is "430" it will return me "some information2".
I've searched a lot on google but by now i dont know if this is even possible.
Appreciate any help.
This is a sample on how to do that. Comments in code can be used to explain the execution.
// Sample Array
$arr = array(
array
(
"value" => 405,
"information" => "some information1"
),
array
(
"value" => 500,
"information" => "some information2"
),
array
(
"value" => 700,
"information" => "some information3"
)
);
// Sample Number
$numberToCheck = 430;
// Sub Array To Assign
$subArray = array();
// Loop Through Outer Array
for ( $i = 0; $i < sizeof($arr); $i++)
{
// If Value In Array > Number Check
if ( $arr[$i]['value'] >= $numberToCheck )
{
$subArray = $arr[$i]; // Assign Sub Array
$i = sizeof($arr); // This is Used to Exit For Loop
}
}
print_r($subArray); // Print
Working runnable code: https://tech.io/snippet/QJ93AwV
Code snippent with comments:
<?php
/**
* Helper class for stable sort alogithms
* #see https://github.com/vanderlee/PHP-stable-sort-functions
* Class StableSort
*/
class StableSort
{
static public function usort(array &$array, $value_compare_func)
{
$index = 0;
foreach ($array as &$item) {
$item = array($index++, $item);
}
$result = usort($array, function ($a, $b) use ($value_compare_func) {
$result = call_user_func($value_compare_func, $a[1], $b[1]);
return $result == 0 ? $a[0] - $b[0] : $result;
});
foreach ($array as &$item) {
$item = $item[1];
}
return $result;
}
}
$array = [
// added for test sorting
[
'value' => 9999,
'information' => 'some information-1',
],
[
'value' => 1200,
'information' => 'some information0',
],
// \added for test sorting
[
'value' => 405,
'information' => 'some information1',
],
// added for test sorting stability
[
'value' => 405,
'information' => 'some information1.2',
],
[
'value' => 405,
'information' => 'some information1.1',
],
// \added for test sorting stability
[
'value' => 500,
'information' => 'some information2',
],
[
'value' => 700,
'information' => 'some information3',
],
];
// sort array
$determinedvalue = 430;
StableSort::usort($array, function ($item1, $item2) {
if ($item1['value'] == $item2['value']) return 0;
return $item1['value'] < $item2['value'] ? -1 : 1;
});
// then select the first element by condition
$res = null;
foreach($array as $v) {
if($v['value'] >= $determinedvalue) {
$res = $v['information'];
break;
}
}
// for testing
print $res;
$number = 430;
$array = Array
[0] => Array
(
[value] => 405
[information] => some information1
)
[1] => Array
(
[value] => 500
[information] => some information2
)
[2] => Array
(
[value] => 700
[information] => some information3
)
$firstArray = $array[0];
$secondArray = $array[1];
$threeArray = $array[2];
function selectValueFromArrayRange ($number, $start, $end, $value, $infomation)
{
$startValue = $start[$value];
$endValue = $end[$value];
if ( in_array($number, range($startValue, $endValue)) ) {
return $end[$infomation];
}
}
selectValueFromArrayRange($number, $firstArray, $secondValue, 'value', 'infomation')
I have an Multidimensional array that takes a similar form to this array bellow.
$shop = array( array( Title => "rose",
Price => 1.25,
Number => 15
),
array( Title => "daisy",
Price => 0.75,
Number => 25,
),
array( Title => "orchid",
Price => 1.15,
Number => 7
)
);
I would like to see if a value I'm looking for is in the array, and if so, return the position of the element in the array.
Here's a function off the PHP Manual and in the comment section.. Works like a charm.
<?php
function recursive_array_search($needle,$haystack) {
foreach($haystack as $key=>$value) {
$current_key=$key;
if($needle===$value OR (is_array($value) && recursive_array_search($needle,$value) !== false)) {
return $current_key;
}
}
return false;
}
Found this function in the PHP docs: http://www.php.net/array_search
A more naive approach than the one showed by Zander, you can hold a reference to the outer key and inner key in a foreach loop and store them.
$outer = "";
$inner = "";
foreach($shop as $outer_key => $inner_array){
foreach($inner_array as $inner_key => $value) {
if($value == "rose") {
$outer = $outer_key;
$inner = $inner_key;
break 2;
}
}
}
if(!empty($outer)) echo $shop[$outer][$inner];
else echo "value not found";
You can use array_map with in_array and return the keys you want
$search = 1.25;
print_r(
array_filter(array_map(function($a){
if (in_array($search, $a)){
return $a;
}
}, $shop))
);
Will print:
Array
(
[0] => Array
(
[Title] => rose
[Price] => 1.25
[Number] => 15
)
)
php >= 5.5
$shop = array( array( 'Title' => "rose",
'Price' => 1.25,
'Number' => 15
),
array( 'Title' => "daisy",
'Price' => 0.75,
'Number' => 25,
),
array( 'Title' => "orchid",
'Price' => 1.15,
'Number' => 7
)
);
$titles = array_column($shop,'Title');
if(!empty($titles['rose']) && $titles['rose'] == 'YOUR_SEARCH_VALUE'){
//do the stuff
}
public function getCheckoutForm(){
$arr = array(
'cmd' => '_cart',
'business' => 'some#mail',
'no_shipping' => '1',
'upload' => '1',
'return' => 'url',
'cancel_return' => 'url1',
'no_note' => '1',
'currency_code' => 'url2',
'bn' => 'PP-BuyNowBF');
$cpt=1;
foreach($this->items as $item){
$arr1[] = array(
'item_number_'.$cpt.'' => $item['item_id'],
'item_name_'.$cpt.'' => $item['item_name'],
'quantity_'.$cpt.'' => $item['item_q'],
'amount_'.$cpt.'' => $item['item_price']
);
$cpt++;
}
return array_merge($arr,$arr1[0],$arr1[1]);
}
This returns array like that:
Array
(
[cmd] => _cart
[business] => some#mail
[no_shipping] => 1
[upload] => 1
[return] => url1
[cancel_return] =>url2
[no_note] => 1
[currency_code] => EUR
[bn] => PP-BuyNowBF
[item_number_1] => 28
[item_name_1] => item_name_1
[quantity_1] => 1
[amount_1] => 5
[item_number_2] => 27
[item_name_2] => item_name_2
[quantity_2] => 1
[amount_2] => 30
)
The problem is that in return $arr1[0] and $arr1[1] are hardcoded. And if in loop i have more than 2 arrays, lets say 0,1,2,3 ans so on, this code won't work. Any idea? Maybe my logic is compleatly wrong...
There's no need to create arrays in your loop - just add new keys directly to the first array:
public function getCheckoutForm(){
$arr = array(
'cmd' => '_cart',
'business' => 'some#mail',
'no_shipping' => '1',
'upload' => '1',
'return' => 'url',
'cancel_return' => 'url1',
'no_note' => '1',
'currency_code' => 'url2',
'bn' => 'PP-BuyNowBF'
);
$cpt=1;
foreach($this->items as $item){
$arr['item_number_'.$cpt] = $item['item_id'];
$arr['item_name_'.$cpt] = $item['item_name'];
$arr['quantity_'.$cpt] = $item['item_q'];
$arr['amount_'.$cpt] = $item['item_price'];
$cpt++;
}
return $arr;
}
I would probably do something like
$count = count($arr1);
for($i=0;$i<$count;$i++){
$arr = array_merge($arr,$arr1[$i]);
}
return $arr;
I hope, I understood, what you mean ^^
foreach ($i = 0, $n = count($arr1); $i < $n; $i++) {
$arr = array_merge($arr, $arr1[$i]);
}
return $arr;
You could do the merge in every iteration:
foreach($this->items as $item){
$temp_arr = array(
'item_number_'.$cpt.'' => $item['item_id'],
'item_name_'.$cpt.'' => $item['item_name'],
'quantity_'.$cpt.'' => $item['item_q'],
'amount_'.$cpt.'' => $item['item_price']
);
$arr = array_merge($arr,$temp_arr)
$cpt++;
}
which has the advantage that you could possibly get $temp_arr from a function,
or just add all the elements to one array:
foreach($this->items as $item){
$arr['item_number_'.$cpt.''] => $item['item_id'];
$arr['item_name_'.$cpt.''] => $item['item_name'];
$arr['quantity_'.$cpt.''] => $item['item_q'];
$arr['amount_'.$cpt.''] => $item['item_price'];
$cpt++;
}
do this
$count = count($data);
$sum = 1;
$arr = [];
for($i=0;$i<$count;$i++){
$temp = $arr;
if($i == $count - 1){
$sum = 0;
}
$arr = array_merge($temp,$data[$i + $sum]);
}
return $arr;