How can I check the value of nested items of array? - php

I have a array like this:
Array
(
[0] => Array
(
[score] => 80
[seen] => 1
)
[1] => Array
(
[score] => 4
[seen] => 1
)
[2] => Array
(
[score] => 4
[seen] => 0
)
[3] => Array
(
[score] => 4
[seen] => 0
)
[4] => Array
(
[score] => 4
[seen] => 0
)
)
I need to check whether is there any [seen] = 1 or not?
if ( /* ??? */ ){
echo "Yes, at least one of [seen] keys is 1";
} else {
echo "No, all [seen] keys are 0";
}
How can I create that condition ?

Using a simple foreach loop can help you
foreach ($array as $arr) {
if ($arr['seen']==1){
echo 'SEEN';
}
}

$seen = false;
foreach($my_array as $el){
if($el['seen']){
$seen = true;
break;
}
}
$seen is true if at least one of [seen] keys is 1
$seen is false if all [seen] keys are 0

Taking a functional approach, you can filter the array using a function that tests for 'seen' == 1. Then if the resulting array is non-empty, you know there are some elements that have 'seen' == 1 values.
<?php
$ar = array(
0 => array(
'score' => 80,
'seen' => 1 ),
1 => array(
'score' => 4,
'seen' => 1 ),
2 => array(
'score' => 4,
'seen' => 0 )
);
if ( array_filter($ar, function($x) { return $x['seen'] == 1; }) ){
echo "Yes, at least one of [seen] keys is 1";
} else {
echo "No, all [seen] keys are 0";
}
?>
Of course, this method is less efficient than those which break out of a loop as soon as a single 'seen' == 1 element is found. But it does give you a single expression in your conditional.

$seen = in_array(1, array_column($array, 'seen'));
Documentation:
array_column()
in_array()

Related

unset array key and rearrange the key

This is how my array looks like :
Array
(
[0] => Array
(
[unit] => 10
[harga] => 15000
)
[1] => Array
(
[unit] => 7
[harga] => 10000
)
[2] => Array
(
[unit] => 12
[harga] => 123123
)
)
I want to unset the 0 key array when the unit is 0 and rearrange the key so the 1 key will replace the 0.
This is how I do it :
$jumlah_penjualan = $data - > unit;
while ($jumlah_penjualan > 0) {
$persediaan_pertama = $persediaan[0]['unit'];
$harga_persediaan = $persediaan[0]['harga'];
if ($persediaan_pertama < $jumlah_penjualan) {
$dijual = $persediaan_pertama;
$penjualan[] = array(
'unit' => $dijual,
'harga' => $harga_persediaan,
'total' => $dijual * $harga_persediaan);
$persediaan[0]['unit'] = $persediaan[0]['unit'] - $dijual;
} else {
$dijual = $jumlah_penjualan;
$penjualan[] = array(
'unit' => $dijual,
'harga' => $harga_persediaan,
'total' => $dijual * $harga_persediaan);
$persediaan[0]['unit'] = $persediaan[0]['unit'] - $dijual;
}
if ($persediaan[0]['unit'] == 0) {
unset($persediaan[0]);
$persediaan = array_values($persediaan);
}
$jumlah_penjualan = $jumlah_penjualan - $dijual;
}
But the result looks like it continues looping before rearranging the array.
This is how the array should look like after unset:
Array(
[0] => Array
(
[unit] => 9
[harga] => 123123
)
)
If you want to remove the first elements until the unit is not 0, you can
$arr = array
(
array
(
"unit" => 0,
"harga" => 15000
),
array
(
"unit" => 0,
"harga" => 10000
),
array
(
"unit" => 12,
"harga" => 123123
)
);
while( $arr[0]["unit"] == 0 ) { //Loop until $arr[0]["unit"] is not 0
unset($arr[0]); //Remove $arr[0] since unit is 0
$arr = array_values($arr); //Make Make element 1 to element 0
}
echo "<pre>";
print_r( $arr );
echo "</pre>";
This will result to:
Array
(
[0] => Array
(
[unit] => 12
[harga] => 123123
)
)
To remove the first element of an array and reindex the elements, use array_shift. First, check that the number of units are zero, then remove the first element if that's the case.
if ($arr[0]['unit'] == 0) {
array_shift($arr);
}
Since it's impossible to say what your other variables even mean because of the language, you probably want to move this outside of your while loop, so that the first element is only removed after you've processed the array.

How to Sum Groupped Element Within array in PHP

Let's say I have this array in PHP
Array(
[0] => Array
(
[DLVRD] => 2
[FAILED] => 1
[REJECT] => 4
[QUEUED] => 5
)
[1] => Array
(
[DLVRD] => 5
[FAILED] => 0
[REJECT] => 3
[QUEUED] => 2
)
[2] => Array
(
[DLVRD] => 3
[FAILED] => 0
[REJECT] => 1
[QUEUED] => 3
)
)
And I want to do is to have result something like this
Array
(
[DLVRD] => 10
[FAILED] => 1
[OTHERS] => 8
)
Currently my PHP code is like this:
foreach($GetTelcosRevenue as $telco) {
if($telco['dr_detail'] == 'DLVRD') {
$TelcoRevenue .="DLVRD:".$telco['TheTraffics'].",";
}
else if($telco['dr_detail'] == 'FAILED') {
$TelcoRevenue .="FAILED:".$telco['TheTraffics'].",";
}
else {
?????
}
}
}
I have tried to put $Others += $telco['TheTraffics'] and other hacks but I still got wrong result. Thanks for any help
You can do, by this way :
$sum = array();
foreach ($array as $k=>$sub) { // $array is your question array
foreach ($sub as $id=>$value) {
$sum[$id]+=$value;
}
}
print_r($sum);

php checking if value exist in a 2 level multidimensional array

I have this array:
Array
(
[01] => Array
(
[cat_id] => 15
[offset] => 4951
)
[02] => Array
(
[cat_id] => 15
[offset] => 4251
)
[03] => Array
(
[cat_id] => 15
[offset] => 4001
)
[04] => Array
(
[cat_id] => 15
[offset] => 4951
)
[05] => Array
(
[cat_id] => 15
[offset] => 3301
)
)
I have the code to get the key on first level using array_key_exists;
if ((array_key_exists("01", $completed_steps))) {
echo "Found 0!";
}
But I want now to get the cat_id value, how could I do that in a level 2 array?
Use below code, it will find key to n-level depth and search for given key
function multiKeyExists(array $arr, $key) {
// is in base array?
if (array_key_exists($key, $arr)) {
return $arr[$key]['cat_id']; // returned cat_id
}
// check arrays contained in this array
foreach ($arr as $element) {
if (is_array($element)) {
if (multiKeyExists($element, $key)) {
return $element[$key]['cat_id']; // returned cat_id
}
}
}
return false;
}
Try like this:
if ((array_key_exists('cat_id', $completed_steps['01'])) {
echo $completed_steps['01']['cat_id'];
}
You can get particular key-value from it index. See following example:
$check_key = "01";
if ((array_key_exists($check_key, $completed_steps))) {
echo "Found 0! value of cat_id = ".$completed_steps[$check_key]['cat_id'];
}
use the code below
$final_cat_id_array = array();
$key_to_check = 'cat_id';
$catFunc = function($currentArr) use (&$final_cat_id_array, $key_to_check){
if(is_array($currentArr) && array_key_exists($key_to_check, $currentArr)){
$final_cat_id_array[] = $currentArr[$key_to_check];
}
};
$arr = array(
"01" => array("cat_id" => 1, "offset" => true),
"02" => array("cat_id" => 2, "offset" => false),
"03" => array("cat_id" => 3, "offset" => true),
);
array_walk($arr, $catFunc);
print_r($final_cat_id_array);
the final $final_cat_id_array will have all the cat_id.

Add item to array of arrays based on id

I have an array of arrays set up like so. There are a total of 10 arrays but I will just display the first 2. The second column has a unique id of between 1-10 (each only used once).
Array
(
[0] => Array
(
[0] => User1
[1] => 5
)
[1] => Array
(
[0] => User2
[1] => 3
)
)
I have another array of arrays:
Array
(
[0] => Array
(
[0] => 3
[1] => 10.00
)
[1] => Array
(
[0] => 5
[1] => 47.00
)
)
where the first column is the id and the second column is the value I want to add to the first array.
Each id (1-10) is only used once. How would I go about adding the second column from Array#2 to Array#1 matching the ID#?
There are tons of ways to do this :) This is one of them, optimizing the second array for search and walking the first one:
Live example
<?
$first_array[0][] = 'User1';
$first_array[0][] = 5;
$first_array[1][] = 'User2';
$first_array[1][] = 3;
$secnd_array[0][] = 3;
$secnd_array[0][] = 10.00;
$secnd_array[1][] = 5;
$secnd_array[1][] = 47.00;
// Make the user_id the key of the array
foreach ($secnd_array as $sca) {
$searchable_second_array[ $sca[0] ] = $sca[1];
}
// Modify the original array
array_walk($first_array, function(&$a) use ($searchable_second_array) {
// Here we find the second element of the first array in the modified second array :p
$a[] = $searchable_second_array[ $a[1] ];
});
// print_r($first_array);
Assuming that 0 will always be the key of the array and 1 will always be the value you'd like to add, a simple foreach loop is all you need.
Where $initial is the first array you provided and $add is the second:
<?php
$initial = array(array("User1", 5),
array("User2", 3));
$add = array(
array(0, 10.00),
array(1, 47.00));
foreach ($add as $item) {
if (isset($initial[$item[0]])) {
$initial[$item[0]][] = $item[1];
}
}
printf("<pre>%s</pre>", print_r($arr1[$item[0]], true));
I don't know if I got you right, but I've come up with a solution XD
<?php
$array_1 = array(
0 => array(
0 => 'ID1',
1 => 5
),
1 => array(
0 => 'ID2',
1 => 3
)
);
$array_2 = array(
0 => array(
0 => 3,
1 => 10.00
),
1 => array(
0 => 5,
1 => 47.00
)
);
foreach($array_1 as $key_1 => $arr_1){
foreach($array_2 as $key_2 => $arr_2){
if($arr_2[0] == $arr_1[1]){
$array_1[$key_1][2] = $arr_2[1];
}
}
}
var_dump($array_1);
?>
Demo: https://eval.in/201648
The short version would look like this:
<?php
$array_1 = array(array('ID1',5),array('ID2',3));
$array_2 = array(array(3,10.00),array(5,47.00));
foreach($array_1 as $key => $arr_1){
foreach($array_2 as$arr_2){
if($arr_2[0] == $arr_1[1]){
$array_1[$key][2] = $arr_2[1];
}
}
}
var_dump($array_1);
?>
Demo: https://eval.in/201649
Hope that helps :)
A quick and dirty way just to show you one of the more self-explaining ways to do it :)
$users = array(
0 => array(
0 => 'User1',
1 => 123
),
1 => array(
0 => 'User2',
1 => 456
)
);
$items = array(
0 => array(
0 => 123,
1 => 'Stuff 1'
),
1 => array(
0 => 456,
1 => 'Stuff 2'
)
);
foreach($items as $item){
foreach($users as $key => $user){
if($item[0] == $user[1])
array_push($users[$key], $item[1]);
}
}

How to correctly convert an array in PHP with quantity/price data?

I can't seem to wrap my head around this.
I am given an array in PHP that looks something like this:
array (
0 => array (
0 => 50,
1 => 0.80
),
1 => array (
0 => 300,
1 => 0.50
),
2 => array (
0 => 600,
1 => 0.30
),
3 => array (
0 => 1000,
1 => 0.20
),
4 => array (
0 => 4000,
1 => 0.10
)
);
An array of arrays where the first index of the inner array represents a quantity while the second index represents a price.
I want to import this data into my database, but in a specific way.
I have specific quantities that I like to keep track of that are defined by the following array:
array(10,100,500,1000,5000,10000);
I then want to make the original array more fine tuned to quantities and prices that I would like to see. So in this particular example, I would like an array that looks like this:
array (
0 => array (
0 => 100,
1 => 0.80
),
1 => array (
0 => 500,
1 => 0.50
),
2 => array (
0 => 1000,
1 => 0.20
),
3 => array (
0 => 5000,
1 => 0.10
)
);
My new array will only contain the specific quantity indexes.
If a quantity exists in the original array, I use that price. If it doesn't exist, I would use the price of the next lowest quantity. If no lower quantity exists, I don't want to see that quantity in the new array.
I have been able to accomplish what I want for the most part with the following code:
function getRelativePrices($pricearray) {
$relativeprices = array();
$types = array(10,100,500,1000,5000,10000);
foreach ($types as $q) {
$new_array = array();
foreach ($pricearray as $index => $array) {
if ($q >= $array[0]) {
$new_array = array($q, $array[1]);
}
}
if (sizeof($new_array)) {
$relativeprices[] = $new_array;
}
}
return $relativeprices;
}
The only problem with the above is that I am getting extra data that I do not want. In the example I provided, I am getting a 5th index/array at the end that looks like:
4 => array (
0 => 10000,
1 => 0.10
)
I don't want this last piece, since I find it redundant considering that I know that 5000 pieces cost $0.10 each, so I can assume that 10000 will cost the same price when "4000" is the highest quantity given in the original array.
So I want to ask for help in removing this last piece.
Also, I was wondering if someone had a better coding method in general for converting this array.
You could just do in your inner foreach:
foreach ($pricearray as $index => $array) {
if ($q >= $array[0]) {
if($q == 10000) { continue; }
$new_array = array($q, $array[1]);
}
}
OK I think this should do the trick. I think the problem was in your comparison... See code:
function getRelativePrices($pricearray) {
$relativeprices= array();
$types = array(10,100,500,1000,5000,10000);
foreach($pricearray as $p) {
$new_array = array();
foreach($types as $t) {
if($p[0] <= $t) {
$new_array = array($t,$p[1]);
break;
}
}
if(sizeof($new_array)) {
$relativeprices[] = $new_array;
}
}
return $relativeprices;
}
Here is an example of my test based on your code examples:
function getRelativePrices($pricearray) {
$relativeprices= array();
$types = array(10,100,500,1000,5000,10000);
foreach($pricearray as $p) {
$new_array = array();
foreach($types as $t) {
if($p[0] <= $t) {
$new_array = array($t,$p[1]);
break;
}
}
if(sizeof($new_array)) {
$relativeprices[] = $new_array;
}
}
return $relativeprices;
}
$test = array (
0 => array (
0 => 50,
1 => 0.80
),
1 => array (
0 => 300,
1 => 0.50
),
2 => array (
0 => 600,
1 => 0.30
),
3 => array (
0 => 1000,
1 => 0.20
),
4 => array (
0 => 4000,
1 => 0.10
)
);
print_r(getRelativePrices($test));
And the output was:
Array
(
[0] => Array
(
[0] => 100
[1] => 0.8
)
[1] => Array
(
[0] => 500
[1] => 0.5
)
[2] => Array
(
[0] => 1000
[1] => 0.3
)
[3] => Array
(
[0] => 1000
[1] => 0.2
)
[4] => Array
(
[0] => 5000
[1] => 0.1
)
)

Categories