Execute a value once in the for loop - php

In array list [hide] =>1 having 2 times, how to execute a [hide] =>1 only one time in for loop . how to check current array with all previous value and [hide] =>1 execute once in the for loop
need to execute [id] =>4 , no need to execute a [id] => 2 in for loop
Array
Array (
[0] => Array ( [id] => 6 [hide] => 0 )
[1] => Array ( [id] => 5 [hide] => 0 )
[2] => Array ( [id] => 4 [hide] => 1 )
[3] => Array ( [id] => 3 [hide] => 0 )
[4] => Array ( [id] => 2 [hide] => 1 )
)

Try this..... You can use this function for any depth of the associated array.
function is_in_array($array, $key, $key_value){
$within_array = 'no';
foreach( $array as $k=>$v ){
if( is_array($v) ){
$within_array = is_in_array($v, $key, $key_value);
if( $within_array == 'yes' ){
break;
}
} else {
if( $v == $key_value && $k == $key ){
$within_array = 'yes';
break;
}
}
}
return $within_array;
}
print_r(is_in_array($yourarray, 'hide', '1'));

I suppose you want the item with the greatest ID :
// get only the items with 'hide' = 1
$hidden = array_filter($array, function($item){return $item['hide'] == 1;});
// order the array to have the items with the greatest ID first
usort($hidden, function($a, $b){
return $b['id'] - $a['id'] ;
});
// print the item with the max id
print_r($hidden[0]);

for($i = 0; $i<count($array); $i++){
if($array[$i] == 4){
print_r($array[4]);
}
}

Related

Last value condition foreach in array?

I have an array like that:
[0] => Array
(
[sendby] => 3
[refresh] => 0
[last] => 0
)
[1] => Array
(
[sendby] => 3
[refresh] => 1
[last] => 1
)
[2] => Array
(
[sendby] => 8
[refresh] => 1
[last] => 1
)
I want the value last to be 1 when the value sendby (here 3 and 8) is the last of the entire array! How can I do that?
Get the last 2 value and compare with array [3,8]
// get array of sendby values
$temp = array_column($array, 'sendby');
// get array with two last values
$temp = array_slice($temp, -2);
// Check
if ($temp == [3,8]) {
$value = 1;
}
else {
$value = 0;
}
or in one line
$value = array_slice(array_column($array, 'sendby'), -2) == [3,8] ? 1 : 0;
demo
Update on base of comments
// get array with two last values
$temp = array_slice(array_column($array, 'sendby'), -2);
foreach($array as &$x) {
// If current send by is in $temp array
if(in_array($x['sendby'], $temp)) {
$x['last'] = 1;
}
else {
$x['last'] = 0;
}
}
print_r($array);
You can use an array to assist the existing ocurrences of that id. I have an working example (Tested on php sandbox):
$array = array(
0 => array
(
'sendby' => 3,
'refresh' => 0,
),
1 => array
(
'sendby' => 3,
'refresh' => 1,
),
2 => array
(
'sendby' => 8,
'refresh' => 1,
)
);
$ocurrences = [];
foreach($array as $key => $elem ){
$id = $elem['sendby'];
if (isset($ocurrences[$id])) {
$array[$ocurrences[$id]]['last'] = 0;
$array[$key]['last'] = 1;
$ocurrences[$id] = $key;
} else {
$ocurrences[$id] = $key;
$array[$key]['last'] = 1;
}
}
echo print_r($array, 1);
The result:
Array
(
[0] => Array
(
[sendby] => 3
[refresh] => 0
[last] => 0
)
[1] => Array
(
[sendby] => 3
[refresh] => 1
[last] => 1
)
[2] => Array
(
[sendby] => 8
[refresh] => 1
[last] => 1
)
)
Basically I used an array with the ocurrences of the 'sendby' index of the array. The $occurences array has the elements with the key of the last checked element.
Lets suppose your array is $array;
You could iterate through it and if it's the last element, then set [last] to 1, else set to 0;
Try to run the below code after your array is populated.
$i =1;
foreach($array as $ar) {
$ar->last = ($i == count($array) && ($ar->sendby == 3 || $ar->sendby == 8)) ? 1 : 0;
$i++;
}
$count = count($arr) ;
$i = 0;
foreach($arr as $key=>$val) {
if(++$I === $count) {
echo "last element" ;
}
}

How can I delete a subArray, if search values matches?

I am fairly new to working with arrays and I am stuck on being able to delete an entry.
If I have:
$del_itemid = 58;
$del_modiifier = 1;
How do I search through my array $orders and unset the array containing these variables ?
$orders = Array
(
[0] => Array
(
[itemid] => 67
[modifier] => 1
[quantity] => 1
[unit_price] => 17.00
[categoryid] => 2
)
[1] => Array
(
[itemid] => 58
[modifier] => 1
[quantity] => 1
[unit_price] => 18.00
[categoryid] => 5
)
[2] => Array
(
[itemid] => 72
[modifier] => 1
[quantity] => 1
[unit_price] => 10.00
[categoryid] => 3
)
)
EDIT:
This is what I have been trying:
$i = 0;
foreach($orders as $key => $value) {
$itemid = $value['itemid'];
$modifier = $value['modifier'];
if ($itemid == $del_itemid && $modifier == $del_modifier) {
unset($_SESSION['cart'][$i]);
break;
}
$i++;
}
Since you want to check 2 values, I would use array_filter() to loop through the array and filter all subArrays out, where both values are equal to your search values, e.g.
$newArray = array_filter($orders, function($v)use($del_itemid, $del_modiifier){
if($v["itemid"] == $del_itemid && $v["modifier"] == $del_modiifier)
return FALSE;
return TRUE;
});
I found a solution based on what I was originally trying to achieve with the loop. If I use array_splice() instead of unset() it will reset the index so that it remains possible to loop through the array without there being holes in the index:
$i = 0;
foreach($orders as $key => $value) {
$itemid = $value['itemid'];
$modifier = $value['modifier'];
if ($itemid == $del_itemid && $modifier == $del_modifier) {
array_splice($orders, $i,1);
}
$i++;
}

Comparing in an Array: If two highest value exists, then compare the other value

Suppose I have an array like:
array( [0] => array([item]=>apple [buy]=>50 [sell]=>30)
[1] => array([item]=>lemon [buy]=>50 [sell]=>60)
[2] => array([item]=>banana [buy]=>40 [sell]=>20)
[3] => array([item]=>orange [buy]=>20 [sell]=>30)
)
Currently I am using this script to check which item has the most buyer
function getMax($array, $val)
{
$max = 0;
foreach( $array as $k => $v )
{
$max = max( array( $max, $v[$val] ) );
}
return $max;
}
$highestBuy = getMax($thisArray, 'buy');
foreach($thisArray as $i=>element){
if($element['buy'] == $highestBuy){
$thisArray[$i]['highestBuy'] = 'yes';
} else {
$thisArray[$i]['highestBuy'] = 'no';
}
}
In this case, both apple and lemon will have highestBuy a yes value. But now I want to find out which item is the most popular by checking their sell if there are two or more same value of highestBuy. Which is the most simple or fastest way to make the output like:
array([0] => array([item]=>apple [buy]=>50 [sell]=>30 [mostPopular]=>no)
[1] => array([item]=>lemon [buy]=>50 [sell]=>60 [mostPopular]=>yes)
[2] => array([item]=>banana [buy]=>40 [sell]=>20 [mostPopular]=>no)
[3] => array([item]=>orange [buy]=>20 [sell]=>30 [mostPopular]=>no)
)
Thanks in advance.
EDIT:
What I want to do is:
find out the highest buy
If this value occur only once(which means there are one highest buy in the array) then push the [mostPouplar]=>yes into the array
If not(there are two or more same highest value), then find out the highest sell.
That's mean if the highest value is unique, it will stop doing further action. If not, it will keep going to find secondary highest value in an array. Is it possible to achieve this?
Sort array with your rules and take first element
$array = array( '0' => array('item'=>apple, 'buy'=>50 ,'sell'=>30),
'1' => array('item'=>lemon, 'buy'=>50, 'sell'=>60),
'2' => array('item'=>banana, 'buy'=>40, 'sell'=>20),
'3' => array('item'=>orange, 'buy'=>20 ,'sell'=>30)
);
usort($array,
function($a, $b) {
$res = $b['buy'] - $a['buy'];
if (!$res) $res = $b['sell'] - $a['sell'];
return $res; });
result:
Array (
[0] => Array ( [item] => lemon [buy] => 50 [sell] => 60 )
[1] => Array ( [item] => apple [buy] => 50 [sell] => 30 )
[2] => Array ( [item] => banana [buy] => 40 [sell] => 20 )
[3] => Array ( [item] => orange [buy] => 20 [sell] => 30 ) )
I had changed the getMax() to return the index of the most popular item
function getMax($array, $val, $val2)
{
$max_item = 0;
foreach( $array as $k => $v )
{
if($array[$max_item][$val] <= $v[$val] && $array[$max_item][$val2] <= $v[$val2])
$max_item = $k;
}
return $max_item;
}
$highestBuy = getMax($thisArray, 'buy', 'sell');
foreach($thisArray as $i => $element){
$thisArray[$i]['mostPopular'] = ($i == $highestBuy) ? 'yes' : 'no';
}

Foreach through array, do some calculations within the array, then create new array and merge back into original

Having some difficulty trying to do this. I'm fetching an array of all submissions, and they are being returned in an array like this:
Array
(
[0] => Array
(
[Submission] => Array
(
[user_id] => 2
[title] => This is a test, only a test
[source] => http://www.testing.com
[slug] => this-is-a-test-only-a-test
[category] => misc
[created] => 2012-10-05 03:43:11
[id] => 110
)
[SubmissionsVote] => Array
(
[0] => Array
(
[id] => 336
[user_id] => 2
[submission_id] => 110
[vote_type] => up
)
)
(
[1] => Array
(
[id] => 337
[user_id] => 4
[submission_id] => 110
[vote_type] => down
)
)
)
)
My intent is to loop through that returned array, and grab all the SubmissionsVote by vote_type == up and vote_type == down.
I then want to calculate a score (this example would return a score of 0 which is just: up - down. With that, I want to put that score into an array and append it to the end of the original one so it'd look like:
Array
(
[0] => Array
(
[Submission] => Array
(
[user_id] => 2
[title] => This is a test, only a test
[source] => http://www.testing.com
[slug] => this-is-a-test-only-a-test
[category] => misc
[created] => 2012-10-05 03:43:11
[id] => 110
)
[SubmissionsVote] => Array
(
[0] => Array
(
[id] => 336
[user_id] => 2
[submission_id] => 110
[vote_type] => up
)
)
(
[1] => Array
(
[id] => 337
[user_id] => 4
[submission_id] => 110
[vote_type] => down
)
)
[SubmissionScore] => Array
(
[0] => 0
)
)
)
Here is what I am doing unsuccessfully:
$votes = array();
$totalScore = array();
foreach ($submissions as $submission) {
$vote = $submission['SubmissionsVote'];
array_push($votes, $vote);
}
for ($i = 0; $i < count($votes); $i++) {
$downVotes = 0;
$upVotes = 0;
if ($votes[$i]['vote_type'] == 'down') {
$downVotes += 1;
} else if ($votes[$i]['vote_type'] == 'up') {
$upVotes += 1;
}
$score = $upVotes - $downVotes;
$totalScore = array_push($totalScore, $score);
}
Would love to get a little push in the right direction here.
Try this one:
$newSubmissions = array();
foreach ($submissions as $submission) {
$SubmissionsVote = $submission['SubmissionsVote'];
foreach($SubmissionsVote as $votes) {
$score = 0;
if ($votes['vote_type'] == 'down') {
$score -= 1;
} else if ($votes['vote_type'] == 'up') {
$score += 1;
}
$submission['SubmissionScore'] = array($score);
}
$newSubmissions[] = $submission;
}
$submissions = $newSubmissions;
I see at least two errors in your code :
You never set SubmissionScore in your array to $totalScore value.
Even if you add a $votes[$i]['SubmissionScore'] = $totalScore, that will not work, in PHP only object are passed by reference so $votes will only contain copy.
There are multiple possibility to resolve the problem but a reference in the foreach is a good choice :
foreach ($submissions as &$submission) {
$totalScore = 0;
foreach ($submission['SubmissionsVote'] as $vote) {
if ($vote['vote_type'] == 'down') {
$totalScore--;
} else if ($vote['vote_type'] == 'up') {
$totalScore++;
}
}
$submission['SubmissionScore'] = $totalScore;
}
Each submission will now have a SubmissionScore based on up/down vote.
You are initializing $downVotes and $upVotes inside a loop, that means you override values each time you iterate through the array.
Anyway, you could simplify this.
foreach ($submissions as $index => $submission) {
$up = 0;
$down = 0;
foreach ($submission['SubmissionsVote'] as $vote) {
if ($vote['vote_type'] == 'up') {
$up++;
} else {
$down++;
}
}
$submissions[$index]['SubmissionScore'] = $up - $down;
}

calucating the total of the price field in an array

( [0] => Array
( [0] => Array (
[0] => Array ( [price] => 76 )
[1] => Array ( [price] => 200 )
[2] => Array ( [price] => 500 )
[3] => Array ( [price] => 67 )
is there a clean way to calculate all these prices
Doing some digging at the array_sum() manual (reading in the user section) I came across this function:
function array_sum_key( $arr, $index = null ){
if(!is_array( $arr ) || sizeof( $arr ) < 1){
return 0;
}
$ret = 0;
foreach( $arr as $id => $data ){
if( isset( $index ) ){
$ret += (isset( $data[$index] )) ? $data[$index] : 0;
}else{
$ret += $data;
}
}
return $ret;
}
How I would in-vision you using it, given the remarks at the manual
$sum = array_sum_key($products[0][0], 'price');
Hopefully it works out for you, as that should be an easy solution :)

Categories