Created
March 20, 2017 10:35
-
-
Save katoba86/e6f521e74fe8443060b52961388c3749 to your computer and use it in GitHub Desktop.
Array helper methods/functions - flatten / object2array / array2object / recursive unique
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Created by PhpStorm. | |
* User: Kai Bartholome | |
* Date: 20.12.2016 | |
* Time: 15:20 | |
*/ | |
namespace app\components; | |
/** | |
* Class ArrayHelper | |
* @package app\components | |
*/ | |
class ArrayHelper | |
{ | |
/** | |
* @param $array | |
* @param null $key | |
* @return array | |
*/ | |
public static function unique($array,$key = null){ | |
if(null === $key){ | |
return array_unique($array); | |
} | |
$keys=[]; | |
$ret = []; | |
foreach($array as $elem){ | |
$arrayKey = (is_array($elem))?$elem[$key]:$elem->$key; | |
if(in_array($arrayKey,$keys)){ | |
continue; | |
} | |
$ret[] = $elem; | |
array_push($keys,$arrayKey); | |
} | |
return $ret; | |
} | |
/** | |
* @param $object | |
* @return array | |
*/ | |
public static function stdObject2Array($object){ | |
return json_decode(json_encode($object), true); | |
} | |
/** | |
* @param $object | |
* @return \stdClass | |
*/ | |
public static function array2StdObject($object){ | |
return json_decode(json_encode($object), false); | |
} | |
/** | |
* Flatten an array | |
* @param $array | |
* @return array | |
* @throws \Exception | |
*/ | |
public static function flatten($array) | |
{ | |
$returnArray=[]; | |
foreach($array as $key=>$value){ | |
if(!is_array($value) && !is_object($value)) { | |
$returnArray[] = $value; | |
}else if(is_array($value)){ | |
$returnArray = array_merge($returnArray,self::flatten($value)); | |
}else if(is_object($value)){ | |
$value = json_decode(json_encode($value), true); | |
$returnArray = array_merge($returnArray,self::flatten($value)); | |
}else{ | |
throw new \Exception('Unknown value type'); | |
} | |
} | |
return $returnArray; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment