fitness-web/common/helpers/AppArrayHelper.php
2021-10-11 22:32:43 +02:00

56 lines
1.2 KiB
PHP

<?php
namespace common\helpers;
class AppArrayHelper
{
public static function mapValues($array, $func){
$result = [];
foreach ($array as $item){
$result[] = $func($item);
}
return $result;
}
public static function objectArrayToMap($array, $funcGetId, $funcGetValue){
$result = [];
foreach ($array as $item ){
$id = $funcGetId($item);
$value = $funcGetValue($item);
$result[$id] = $value;
}
return $result;
}
/**
* Map an array of object by object id
* [obj1,obj2] => [obj1.id => obj1,obj2.id => obj2]
* @param $array
* @return array
*/
public static function objectArrayToMapById($array){
return AppArrayHelper::objectArrayToMap(
$array,
function ($item){
return $item->id;
},
function ($item){
return $item;
}
);
}
public static function getOrDefault($array, $key, $defaultValue = null){
if ( isset($array[$key])){
return $array[$key];
}
return $defaultValue;
}
}