Associative array remove all values of 0 - php

I have an Associative array in PHP and want to remove all values which have the associated value of 0
Array ( [item1] => 0 [item2] => 10 [item5] => 0 [item10] => 10 [item12] => 5 )
Thank you

Well, there are a lot of ways to achieve this, out of which two I have mentioned below:
Use array_filter.
Snippet:
<?php
$arr = [
'item1' => 0,
'item2' => 10,
'item5' => 0,
'item10' => 10,
'item12' => 5,
'item120' => false,
];
$filtered = array_filter($arr,function($value){
return $value !== 0;
});
print_r($filtered);
Demo: https://3v4l.org/fMsHt
Another way I would suggest is to use array_diff()
Snippet:
<?php
$arr = [
'item1' => 0,
'item2' => 10,
'item5' => 0,
'item10' => 10,
'item12' => 5,
'item120' => false,
];
print_r(array_diff($arr,[0]));
Demo: https://3v4l.org/3YHiX

you can do this simply using array_filter
$data = Array ( 'item1' => 0 ,'item2' => 10, 'item5' => 0, 'item10' => 10, 'item12' => 5 );
echo '<pre>';print_r(array_filter($data));

Related

Group & reorder array elements in PHP

I have a multidimensional array that I want to be regrouped. The array looks like the following.
$originalArray = array
(
'APPLE' => array(
'BASE_PRICE' => 7.5,
'MARKUP' => 1.2
),
'ORANGE' => array
(
'BASE_PRICE' => 0,
'MARKUP' => 4
),
'BANANA' => array
(
'BASE_PRICE' => 0,
'MARKUP' => 6
),
'LIME' => array
(
'BASE_PRICE' => 0,
'MARKUP' => 8
)
);
I want it reordered such that it is grouped into BASE_PRICE and MARKUP as the following.
$newArray = array (
'BASE_PRICE' => array
(
'APPLE' => 7.5,
'ORANGE' => 0,
'BANANA' => 0,
'LIME' => 0
),
'MARKUP' => array
(
'APPLE' => 1.2,
'ORANGE' => 6,
'BANANA' => 4,
'LIME' => 8
)
);
How do I use loops to achieve the new array? Any help would be greatly appreciated.
So far I've tried the following but not getting what I expect.
arsort($originalArray);
You can achieve the desired array by using
foreach ($originalArray as $key => $value) {
$array1['BASE_PRICE'][$key] = $value['BASE_PRICE'];
$array2['MARKUP'][$key] = $value['MARKUP'];
}
$newarray = array_merge($array1,$array2);
Output
Array
(
[BASE_PRICE] => Array
(
[APPLE] => 7.5
[ORANGE] => 0
[BANANA] => 0
[LIME] => 0
)
[MARKUP] => Array
(
[APPLE] => 1.2
[ORANGE] => 4
[BANANA] => 6
[LIME] => 8
)
)
you can use asort function :
function sort_array ($inputArray){
$outputArray = array();
foreach ($inputArray as $index => $value){
$outputArray["BASE_PRICE"][$index] = $value["BASE_PRICE"];
$outputArray["MARKUP"][$index] = $value["MARKUP"];
}
foreach ($outputArray as $value){
asort($value);
asort($value);
}
return $outputArray;
}
var_dump(sort_array($originalArray));
You can use array-reduce function by next way:
<?php
$originalArray = array
(
'APPLE' => array(
'BASE_PRICE' => 7.5,
'MARKUP' => 1.2
),
'ORANGE' => array
(
'BASE_PRICE' => 0,
'MARKUP' => 4
),
'BANANA' => array
(
'BASE_PRICE' => 0,
'MARKUP' => 6
),
'LIME' => array
(
'BASE_PRICE' => 0,
'MARKUP' => 8
)
);
$resultArray = array_reduce(
array_keys($originalArray),
function($accumulator, $key) use($originalArray) {
$accumulator['BASE_PRICE'][$key]=$originalArray[$key]['BASE_PRICE'];
$accumulator['MARKUP'][$key]=$originalArray[$key]['MARKUP'];
return $accumulator;
},[]
);
print_r($resultArray);
?>

Replace array by specific element value

I need to replace my main array elements by 'employee_id'.
I already tried array_replace_recursive() function But It replaces arrays by the default index value.
$merged = array_replace_recursive($empList, $getworkedHrs,
$getErrAttnds);
The arrays look like this:
$empList
array (
0 =>
array (
'employee_id' => '254',
'emp_name' => 'Mary McDonald',
'worked_days' => 0,
'worked_hours' => 0,
'error_attendance' => 0,
),
1 =>
array (
'employee_id' => '255',
'emp_name' => 'Anthony Coffman',
'worked_days' => 0,
'worked_hours' => 0,
'error_attendance' => 0,
),
2 =>
array (
'employee_id' => '316',
'emp_name' => 'cheth aruno',
'worked_days' => 0,
'worked_hours' => 0,
'error_attendance' => 0,
),
)
2nd Array: $getworkedHrs
array (
0 =>
array (
'employee_id' => '254',
'worked_days' => '22',
'worked_hours' => '7.0',
),
1 =>
array (
'employee_id' => '255',
'worked_days' => '8',
'worked_hours' => '7.0',
),
)
3rd array : $getErrAttnds
array (
0 =>
array (
'employee_id' => '316',
'error_attendance' => '1',
),
)
Expected Result Array:
array (
0 =>
array (
'employee_id' => '254',
'emp_name' => 'Mary McDonald',
'worked_days' => 22,
'worked_hours' => 7.0,
'error_attendance' => 0,
),
1 =>
array (
'employee_id' => '255',
'emp_name' => 'Anthony Coffman',
'worked_days' => 8,
'worked_hours' => 7.0,
'error_attendance' => 0,
),
2 =>
array (
'employee_id' => '316',
'emp_name' => 'cheth aruno',
'worked_days' => 0,
'worked_hours' => 0,
'error_attendance' => 1,
),
)
I believe the simplest solution is to merge them in two foreach.
First make the main array associative so that it's easier to get the correct employee.
Then loop the arrays and copy the values.
$empList = array_column($empList, null, 'employee_id');
foreach($getworkedHrs as $entry){
$empList[$entry['employee_id']]['worked_days'] = $entry['worked_days'];
$empList[$entry['employee_id']]['worked_hours'] = $entry['worked_hours'];
}
foreach($getErrAttnds as $entry){
$empList[$entry['employee_id']]['error_attendance'] = $entry['error_attendance'];
}
var_export($empList);
https://3v4l.org/gIXP6

How to yield value with the key?

How to set the key for yielded value? Can the generator have the key as well as array does?
I can easily name keys when returning arrays. It's very useful for PhpUnit dataProviders:
$array = [
'key' => ['value',1,2,3],
'here' => ['a',4,5,6],
'there' => ['b',7,8,9],
];
foreach( $array as $key => $value ){
echo $key."\t=>\t".var_export($value, true)."\n\n\n";
}
but can I do the same using generators?
e.g., how to change the following code?:
function hi()
{
yield ['value',1,2,3];
yield ['a',4,5,6];
yield ['b',7,8,9];
}
$array = hi();
foreach( $array as $key => $value ){
echo $key."\t=>\t".var_export($value, true)."\n\n\n";
}
Currently, the output is:
0 => array (
0 => 'value',
1 => 1,
2 => 2,
3 => 3,
)
1 => array (
0 => 'a',
1 => 4,
2 => 5,
3 => 6,
)
2 => array (
0 => 'b',
1 => 7,
2 => 8,
3 => 9,
)
How can I set the mindful keys for yielded values?
It is easy, yield has documented ability to use keys:
https://www.php.net/manual/en/language.generators.syntax.php
function hi()
{
yield 'key' => ['value',1,2,3];
yield 'here' => ['a',4,5,6];
yield 'there' => ['b',7,8,9];
}
$array = hi();
foreach( $array as $key => $value ){
echo $key."\t=>\t".var_export($value, true)."\n\n\n";
}
The output will have keys, as well as an array does:
key => [
0 => 'value',
1 => 1,
2 => 2,
3 => 3,
]
here => [
0 => 'a',
1 => 4,
2 => 5,
3 => 6,
]
there => [
0 => 'b',
1 => 7,
2 => 8,
3 => 9,
]

Transpose a multidimensional associative array into a multidimensional indexed array sorted against and an external associative key

I need to transpose a multidimensional associative array into a multidimensional indexed array sorted against and an external associative key. In the example below, I need a way to get from the 'input' to the 'expected output'.
I've tried array_match(), array_intersect() but I think I'm missing something. There must be an elegant solution to this but I cannot figure it out.
//Input
$array = array(
array('Volvo' => 22, 'BMW' => 13, 'Saab' => 5, 'Land Rover' => 11),
array('Nissan' => 10, 'Saab' => 4),
array('Land Rover' => 22, 'BMW' => 9, 'Nissan' => 2, 'Ford' => 17)
//...
);
//Expected output
$array_cars = array( // sorted list of unique car names
0 => 'BMW',
1 => 'Ford',
2 => 'Land Rover',
3 => 'Nissan',
4 => 'Saab',
5 => 'Volvo'
//...
);
$compiled_data = array( // 2D matrix, columns: $array, rows: $array_car
array(0 => 13, 2 => 9), // 'BMW'
array(2 => 17), // 'Ford'
array(0 => 11, 2 => 22), // 'Land Rover'
array(1 => 10, 2 => 2), // 'Nissan'
array(0 => 5, 1 => 4), // 'Saab'
array(1 => 22) // 'Volvo'
//...
);
Probably the simplest thing is to just iterate over all the values, sorting them into a car indexed array. You can then use ksort to sort the data:
$output = array();
foreach ($array as $key => $a) {
foreach ($a as $car => $v) {
$output[$car][$key] = $v;
}
}
ksort($output);
$array_cars = array_keys($output);
$compiled_data = array_values($output);
var_export($array_cars);
var_export($compiled_data);
Output:
array (
0 => 'BMW',
1 => 'Ford',
2 => 'Land Rover',
3 => 'Nissan',
4 => 'Saab',
5 => 'Volvo',
)
array (
0 =>
array (
0 => 13,
2 => 9,
),
1 =>
array (
2 => 17,
),
2 =>
array (
0 => 11,
2 => 22,
),
3 =>
array (
1 => 10,
2 => 2,
),
4 =>
array (
0 => 5,
1 => 4,
),
5 =>
array (
0 => 22,
),
)
Demo on 3v4l.org

Extract a row by value from php array

This is my array:
Array (
[0] => Array ( [SocketID] => 1 [SocketName] => Name [SocketDecimal] => 0 [SocketHex] => 00 [SocketAtt] => 1 [Category] => 1 [Value] => 100 [Procentage] => 0 )
[1] => Array ( [SocketID] => 2 [SocketName] => Name2 [SocketDecimal] => 50 [SocketHex] => 32 [SocketAtt] => 1 [Category] => 1 [Value] => 800 [Procentage] => 0 )
[2] => Array ( [SocketID] => 3 [SocketName] => Name3 [SocketDecimal] => 100 [SocketHex] => 64 [SocketAtt] => 1 [Category] => 1 [Value] => 60 [Procentage] => 0 )
)
How can I extract a row by SocketDecimal?
For example: I want to extract row where SocketDecimal = 50 and make new an array only with that row.
foreach($array as $entry) {
if($entry['SocketDecimal'] == 50)
$newArr[] = $entry;
}
$newArr will contain the desired "row". Of course you can manipulate the if-statement depending on which "row" (I'd just call it array entry) you want to extract.
It's not the best way for big data! It's easy for deep multiarrays.
$arr = array(
array('socket_id'=>1,'name'=>'test1'),
array('socket_id'=>2,'name'=>'test2'),
array('socket_id'=>3,'name'=>'test3'),
array('socket_id'=>2,'name'=>'test4')
);
$newArr = array();
foreach($arr as $row){
foreach($row as $key=>$r){
if($key == 'socket_id' && $r==2)
$newArr[] = $row;
}
}
print_r($newArr);
$result = array();
foreach($input as $i){
if($i['SocketDecimal']==50)
$result[]=$i;
}
You can do it by this method
foreach ($yourarray as $key => $value){
$newarray = array("SocketDecimal"=>$value["SocketDecimal"];
}
print_r($newarray);
If your result array is like given below
$arr = array(
array( 'SocketID' => 1, 'SocketName' => 'Name', 'SocketDecimal' => 0, 'SocketHex' => 0, 'SocketAtt' => 1, 'Category' => 1, 'Value' => 100, 'Procentage' => 0 ),
array ( 'SocketID' => 2, 'SocketName' => 'Name2', 'SocketDecimal' => 50, 'SocketHex' => 32, 'SocketAtt' => 1, 'Category' => 1, 'Value' => 800, 'Procentage' => 0 ),
array ( 'SocketID' => 3, 'SocketName' => 'Name3', 'SocketDecimal' => 100, 'SocketHex' => 64, 'SocketAtt' => 1, 'Category' => 1, 'Value' => 60, 'Procentage' => 0 )
);
print_r($arr);
Get row for SocketDecimal=50 by following loop:
<pre>
$resultArr = '';
foreach($arr as $recordSet)
{
if($recordSet['SocketDecimal'] == 50)
{
$resultArr[] = $recordSet;
break;
}
}
</pre>
print_r($resultArr);
break foreach loop so that it will not traverse for all the array when SocketDecimal(50) founded.
You can use array_column + array_search combo
$array = Array (
"0" => Array ( "SocketID" => 1, "SocketName" => "Name", "SocketDecimal" => 0, "SocketHex" => 00, "SocketAtt" => 1, "Category" => 1, "Value" => 100, "Procentage" => 0 ) ,
"1" => Array ( "SocketID" => 2, "SocketName" => "Name2", "SocketDecimal" => 50, "SocketHex" => 32, "SocketAtt" => 1, "Category" => 1, "Value" => 800, "Procentage" => 0 ),
"2" => Array ( "SocketID" => 3, "SocketName" => "Name3", "SocketDecimal" => 100, "SocketHex" => 64, "SocketAtt" => 1, "Category" => 1, "Value" => 60 ,"Procentage" => 0 )
);
var_dump($array[array_search(50,array_column($array,'SocketDecimal'))]);

Categories