Search all navigation items:
$navitems_locations_array = array_unique(array_column($projects, 'location'));
asort($navitems_locations_array);
This works on my localhost but not on live. My server doesn't support it. And I'm using lower version of PHP.
And this is the error:
Fatal error: Call to undefined function array_column()
Any alternative with the same output?
Here is my sample arrray list:
Array( [ name ] => P1 [ description ] => Lorem Ipsum [ location ] => air city[ type ] => high rise[ status ] => new [ tags ] => [ page_url ] => project-1[ image ] => projects/images/p1/project-image.jpg[ timeline ] => )
Try this hope it will help you out. Here we are using array_map for gathering locations.
$locations=array();
array_map(function($value) use (&$locations) {
$locations[]=$value["location"];//we are gathering index location
}, $yourArray);//add your array here in place of $yourArray.
print_r(array_unique($locations));
It is usually useful to read User Contributed Notes on the PHP Manual.
For example below the array_column article, there are several variants of implementations for versions lower than PHP 5.5. Here is the most popular one:
if(!function_exists("array_column"))
{
function array_column($array,$column_name)
{
return array_map(function($element) use($column_name){return $element[$column_name];}, $array);
}
}
But it doesn't support $index_key, so you can find another one there, which does:
if (!function_exists('array_column')) {
function array_column($input, $column_key, $index_key = null) {
$arr = array_map(function($d) use ($column_key, $index_key) {
if (!isset($d[$column_key])) {
return null;
}
if ($index_key !== null) {
return array($d[$index_key] => $d[$column_key]);
}
return $d[$column_key];
}, $input);
if ($index_key !== null) {
$tmp = array();
foreach ($arr as $ar) {
$tmp[key($ar)] = current($ar);
}
$arr = $tmp;
}
return $arr;
}
}
You can find a couple more alternatives in the User Contributed Notes.
Add your own function array_column if you PHP version does not support it:
if (!function_exists('array_column')) {
function array_column($input = null, $columnKey = null, $indexKey = null)
{
$argc = func_num_args();
$params = func_get_args();
if ($argc < 2) {
trigger_error("array_column() expects at least 2 parameters, {$argc} given", E_USER_WARNING);
return null;
}
if (!is_array($params[0])) {
trigger_error(
'array_column() expects parameter 1 to be array, ' . gettype($params[0]) . ' given',
E_USER_WARNING
);
return null;
}
if (!is_int($params[1])
&& !is_float($params[1])
&& !is_string($params[1])
&& $params[1] !== null
&& !(is_object($params[1]) && method_exists($params[1], '__toString'))
) {
trigger_error('array_column(): The column key should be either a string or an integer', E_USER_WARNING);
return false;
}
if (isset($params[2])
&& !is_int($params[2])
&& !is_float($params[2])
&& !is_string($params[2])
&& !(is_object($params[2]) && method_exists($params[2], '__toString'))
) {
trigger_error('array_column(): The index key should be either a string or an integer', E_USER_WARNING);
return false;
}
$paramsInput = $params[0];
$paramsColumnKey = ($params[1] !== null) ? (string) $params[1] : null;
$paramsIndexKey = null;
if (isset($params[2])) {
if (is_float($params[2]) || is_int($params[2])) {
$paramsIndexKey = (int) $params[2];
} else {
$paramsIndexKey = (string) $params[2];
}
}
$resultArray = array();
foreach ($paramsInput as $row) {
$key = $value = null;
$keySet = $valueSet = false;
if ($paramsIndexKey !== null && array_key_exists($paramsIndexKey, $row)) {
$keySet = true;
$key = (string) $row[$paramsIndexKey];
}
if ($paramsColumnKey === null) {
$valueSet = true;
$value = $row;
} elseif (is_array($row) && array_key_exists($paramsColumnKey, $row)) {
$valueSet = true;
$value = $row[$paramsColumnKey];
}
if ($valueSet) {
if ($keySet) {
$resultArray[$key] = $value;
} else {
$resultArray[] = $value;
}
}
}
return $resultArray;
}
}
Reference:
Related
I am creating my own custom cookie class and I can not seem to figure out what I am doing wrong. Here is my cookie class:
<?php
class Cookie implements CookieHandlerInterface {
private $_domain;
private $_secure;
public function __construct(array $config = array()) {
$this->_domain = isset($config['domain']) ? $config['domain'] : 'localhost';
$this->_secure = isset($config['secure']) ? $config['secure'] : false;
}
public function set($name, $value = null, $timeLength) {
if (!is_null($value)) {
if (is_array($value)) {
if ($this->__isMultiArray($array)) {
return null;
} else {
$value = $this->__arrayBuild($value);
$value = 'array(' . $value . ')';
}
} elseif (is_bool($value)) {
if ($value) {
$value = 'bool(true)';
} else {
$value = 'bool(false)';
}
} elseif (is_int($value)) {
$value = 'int(' . strval($value) . ')';
} elseif (is_float($value)) {
$value = 'float(' . strval($value) . ')';
} elseif (is_string($value)) {
$value = 'string(' . $value . ')';
} else {
return null;
}
} else {
$value = 'null(null)';
}
setcookie($name, $value, (time() + $timeLength), '/', $this->_domain, $this->_secure, true);
}
public function get($name, $defualtOutput = null) {
if (isset($_COOKIE[$name])) {
$output = rtrim($_COOKIE[$name], ')');
$xr1 = mb_substr($output, 0, 1);
if (equals($xr1, 'a')) {
$output = ltrim($output, 'array(');
return $this->__arrayBreak($output);
}
if (equals($xr1, 'b')) {
$output = ltrim($output, 'bool(');
if (equals($output, 'true')) {
return true;
} else {
return false;
}
}
if (equals($xr1, 'i')) {
$output = ltrim($output, 'int(');
return (int) $output;
}
if (equals($xr1, 'f')) {
$output = ltrim($output, 'float(');
return (float) $output;
}
if (equals($xr1, 's')) {
$output = ltrim($output, 'string(');
return $output;
}
if (equals($output, 'null(null)')) {
return null;
}
}
if (
!is_array($defualtOutput)
&& !is_bool($defualtOutput)
&& !is_int($defualtOutput)
&& !is_float($defualtOutput)
&& !is_string($defualtOutput)
&& !is_null($defualtOutput)
) {
trigger_error(
'The $defualtOutput var needs to be only certain types of var types. Allowed (array, bool, int, float, string, null).',
E_USER_ERROR
);
}
return $defualtOutput;
}
public function delete($name) {
if (isset($_COOKIE[$name])) {
setcookie($name, '', time() - 3600, '/', $this->_domain, $this->_secure, true);
}
}
private function __arrayBuild($array) {
$out = '';
foreach ($array as $index => $data) {
$out .= ($data != '') ? $index . '=' . $data . '|' : '';
}
return rtrim($out, '|');
}
private function __arrayBreak($cookieString) {
$array = explode('|', $cookieString);
foreach ($array as $i => $stuff) {
$stuff = explode('=', $stuff);
$array[$stuff[0]] = $stuff[1];
unset($array[$i]);
}
return $array;
}
private function __isMultiArray($array) {
foreach ($array as $key => $value) {
if (is_array($value)) {
return true;
}
}
return false;
}
}
?>
I set a test cookie for example app('cookie')->set('test', 'hello', 0);
sure enough it created the cookie like expected. So the cookie reads string(hello)
When I try to echo it, it echos the default value instead of the actual variable, so app('cookie')->get('test', 'test'); returns test
The get function should check if the cookie exists with isset($_COOKIE[$cookieName]) and then it should trim the extra ) with rtrim($_COOKIE[$cookieName], ')') then it should grab the first character in the string with mb_substr($_COOKIE[$cookieName], 0, 1) the 0 starts at the beginning and the 1 grabs only the first character.
After it compares it with the default (a, b, i, f, s) for example if it starts with an s its a string by default, if it was i it was sent as an int by default, etc. etc.
If they all come up as false it checks to see if it was sent as null if so it return null else it returns the default value passed.
The equals function is the same as $var1 == $var2 it is timing attack safe.
so it keeps returning the default value which is null, any help would be helpful thanks in advance.
Lol i feel real stupid i put 0 as the third argument thinking it will tell the cookie to expire when the browser session closes, but it did (time() + 0) which does not equal 0. so as it was setting the cookie it expired upon creation. So i did time() - (time() * 2). i achieved the goal i wanted.
I'm looking for an easy solution to create a little function to merge two arrays with value concat (I'm using it to create html tag attribute):
$default["class"] = "red";
$new["class"] = "green";
$new["style"] = "display:block"
The result:
$res["class"] = "red green";
$res["style"] = "display: block";
and one more option:
if the $new is not an array, just concat with the $default["class"] (if this exist), and the other side: if the $default is a simple string, convert to array: $default["class"] = $default;
I created a function but would like to use an easier, shorter way for that:
function attrMerge( $default, $new="" ){
$res = array();
if(!is_array($default)) {
$res["class"] = $default;
}
else {
$res = $default;
}
if( $new !== "" ){
if(!is_array($new)) {
if(isset($res["class"])){
$res["class"].= " ".$new;
}
}
else {
foreach($new as $key=>$value) {
if( isset($res[$key]) ) {
$res[$key].= " ".$value;
}
else {
$res[$key] = $value;
}
}
}
}
return $res;
}
$a = attrMerge("red", array("class"=>"green", "style"=>"display: block;"));
I think this is the function that you need. I have initialised the css classes and styles as empty and in depends what you pass into the function then you get the relevant array
/**
* This function returns an array of classes and styles
*
* #param $default
* #param $new
* #return array
*/
function attrMerge($default=null, $new=nul)
{
$result = array();
$result['class'] = "";
$result['style'] = "";
// add default class if exists
if (!empty($default) && is_string($default)) {
// $default is string
$result['class'] = $default;
}
if (!empty($default)
&& is_array($default)
) {
if (array_key_exists('class', $default)
&& !empty($default['class'])
) {
// $default['class'] exists and it's not empty
$result['class'] = $default['class'];
}
if (array_key_exists('style', $default)
&& !empty($default['style'])
) {
// $default['style'] exists and it's not empty
$result['style'] = $default['style'];
}
}
// add additional classes OR styles
if (!empty($new)) {
if(!is_array($new)) {
$result['class'] = empty($result['class'])
? $new
: $result['class'] . " " . $new;
} else {
foreach ($new as $key => $value) {
if (isset($result[$key])) {
$result[$key] = empty($result[$key])
? $value
: $result[$key] . " " . $value;
} else {
$result[$key] = $value;
}
}
}
}
return $result;
}
A way I believe suits your need, hopefully it's as adaptable and effecient as you were expecting.
$array1 = array(
'class' => 'class1',
'style' => 'display: none;'
);
$array2 = array(
'class' => 'class2'
);
$arrayFinal = arrayMerge($array1, $array2);
var_dump($arrayFinal);
function arrayMerge($arr1, $arr2 = ''){
// Array of attributes to be concatenated //
$attrs = array('class');
if(is_array($arr2)){
foreach($attrs as $attr){
if(isset($arr1[$attr]) && isset($arr2[$attr])){
// Not using .= to allow for smart trim (meaning empty check etc isn't needed //
$arr1[$attr] = trim($arr1[$attr] . ' ' . $arr2[$attr]);
}
}
}else{
$arr1['class'] = trim($arr1['class'] . ' ' . $arr2);
}
return $arr1;
}
$def = ['class' => 'red'];
$new = ['class' => 'green', 'style' => 'style'];
function to_array($in) {
return is_array($in) ? $in : ['class' => $in];
}
$def = to_array($def);
$new = to_array($new);
$res = $def;
array_walk($new, function ($val, $key) use (&$res) {
$res[$key] = trim(#$res[$key] . ' ' . $val);
});
var_dump($res);
I have a multidimensional array. I need a function that checks if a specified key exists.
Let's take this array
$config['lib']['template']['engine'] = 'setted';
A function should return true when I call it with:
checkKey('lib','template','engine');
//> Checks if isset $config['lib']['template']['engine']
Note that my array isn't only 3 dimensional. It should be able to check even with only 1 dimension:
checkKey('genericSetting');
//> Returns false becase $c['genericSetting'] isn't setted
At the moment I am using an awful eval code, I would like to hear suggest :)
function checkKey($array) {
$args = func_get_args();
for ($i = 1; $i < count($args); $i++) {
if (!isset($array[$args[$i]]))
return false;
$array = &$array[$args[$i]];
}
return true;
}
Usage:
checkKey($config, 'lib', 'template', 'engine');
checkKey($config, 'genericSetting');
I created the following two functions to do solve the same problem you are having.
The first function check is able to check for one/many keys at once in an array using a dot notation. The get_value function allows you to get the value from an array or return another default value if the given key doesn't exist. There are samples at the bottom for basic usage. The code is mostly based on CakePHP's Set::check() function.
<?php
function check($array, $paths = null) {
if (!is_array($paths)) {
$paths = func_get_args();
array_shift($paths);
}
foreach ($paths as $path) {
$data = $array;
if (!is_array($path)) {
$path = explode('.', $path);
}
foreach ($path as $i => $key) {
if (is_numeric($key) && intval($key) > 0 || $key === '0') {
$key = intval($key);
}
if ($i === count($path) - 1 && !(is_array($data) && array_key_exists($key, $data))) {
return false;
}
if (!is_array($data) || !array_key_exists($key, $data)) {
return false;
}
$data =& $data[$key];
}
}
return true;
}
function get_value($array, $path, $defaultValue = FALSE) {
if (!is_array($path))
$path = explode('.', $path);
foreach ($path as $i => $key) {
if (is_numeric($key) && intval($key) > 0 || $key === '0')
$key = intval($key);
if ($i === count($path) - 1) {
if (is_array($array) && array_key_exists($key, $array))
return $array[$key];
else
break;
}
if (!is_array($array) || !array_key_exists($key, $array))
break;
$array = & $array[$key];
}
return $defaultValue;
}
// Sample usage
$data = array('aaa' => array(
'bbb' => 'bbb',
'ccc' => array(
'ddd' => 'ddd'
)
));
var_dump( check($data, 'aaa.bbb') ); // true
var_dump( check($data, 'aaa.bbb', 'aaa.ccc') ); // true
var_dump( check($data, 'zzz') ); // false
var_dump( check($data, 'aaa.bbb', 'zzz') ); // false
var_dump( get_value($data, 'aaa.bbb', 'default value') ); // "bbb"
var_dump( get_value($data, 'zzz', 'default value') ); // "default value"
i have this code. Basically identifies if any position of array is empty or have an input equal a zero.
$fields = array("first", "second", "third");
function check($fields, $form) {
foreach($fields as $field) {
if(empty($form[$field]) || $form[$field] === 0) {
echo 'empty';
return false;
break;
}
}
}
My doubt now, is , how i can do an echo for example to show the second position is empty?
with an if? if ($form[$field][second]) ? i don't know if this is correct, or exists a better option
thanks
if $field is what you want to echo then just prepend it to 'is empty':
$fields = array("first", "second", "third");
function check($fields, $form)
{
foreach($fields as $field)
{
if(empty($form[$field]))
{
echo $field.' is empty';
return false;
}
}
}
if you need the index value:
$fields = array("first", "second", "third");
function check($fields, $form)
{
foreach($fields as $k=>$field)
{
if(empty($form[$field]))
{
echo $k.' is empty';
return false;
}
}
}
eventually if the aim is retrieve the empty position (if check returns -1 then there are no empty positions):
$fields = array("first", "second", "third");
function check($fields, $form)
{
foreach($fields as $k=>$field)
{
if(empty($form[$field]))
return $k;
}
return -1;
}
Can't you do something like the following:
if (empty($form[$field+1])) {
echo 'Empty';
}
Use a recursive function like this:
function isEmpty($array){
if(is_array($array)){
foreach($array as $key=>$value){
if(isEmpty($value) !== false) return $key;
}
return false;
}else{
if($array === 0 || empty($array)){
return true;
}
}
}
This will traverse the array as deep as it goes, and return the index where it found an empty position, or false if it did not find an empty position.
Maybe I'm in totally wrongness, but why not :
if(empty($form[2]) || $form[2] === 0) {
echo 'second element is empty';
}
If your question is 'How can I know at what index am I while doing a foreach', then the answer is that :
$fields = array("first", "second", "third");
function check($fields, $form) {
foreach($fields as $i => $field) {
if ( (empty($form[$field]) || $form[$field] === 0) && ($i == 2)) {
echo '2n element is empty';
return false; // no need to break; as you have returned something.
}
}
}
I have a multidimensional array. I need a function that checks if a specified key exists.
Let's take this array
$config['lib']['template']['engine'] = 'setted';
A function should return true when I call it with:
checkKey('lib','template','engine');
//> Checks if isset $config['lib']['template']['engine']
Note that my array isn't only 3 dimensional. It should be able to check even with only 1 dimension:
checkKey('genericSetting');
//> Returns false becase $c['genericSetting'] isn't setted
At the moment I am using an awful eval code, I would like to hear suggest :)
function checkKey($array) {
$args = func_get_args();
for ($i = 1; $i < count($args); $i++) {
if (!isset($array[$args[$i]]))
return false;
$array = &$array[$args[$i]];
}
return true;
}
Usage:
checkKey($config, 'lib', 'template', 'engine');
checkKey($config, 'genericSetting');
I created the following two functions to do solve the same problem you are having.
The first function check is able to check for one/many keys at once in an array using a dot notation. The get_value function allows you to get the value from an array or return another default value if the given key doesn't exist. There are samples at the bottom for basic usage. The code is mostly based on CakePHP's Set::check() function.
<?php
function check($array, $paths = null) {
if (!is_array($paths)) {
$paths = func_get_args();
array_shift($paths);
}
foreach ($paths as $path) {
$data = $array;
if (!is_array($path)) {
$path = explode('.', $path);
}
foreach ($path as $i => $key) {
if (is_numeric($key) && intval($key) > 0 || $key === '0') {
$key = intval($key);
}
if ($i === count($path) - 1 && !(is_array($data) && array_key_exists($key, $data))) {
return false;
}
if (!is_array($data) || !array_key_exists($key, $data)) {
return false;
}
$data =& $data[$key];
}
}
return true;
}
function get_value($array, $path, $defaultValue = FALSE) {
if (!is_array($path))
$path = explode('.', $path);
foreach ($path as $i => $key) {
if (is_numeric($key) && intval($key) > 0 || $key === '0')
$key = intval($key);
if ($i === count($path) - 1) {
if (is_array($array) && array_key_exists($key, $array))
return $array[$key];
else
break;
}
if (!is_array($array) || !array_key_exists($key, $array))
break;
$array = & $array[$key];
}
return $defaultValue;
}
// Sample usage
$data = array('aaa' => array(
'bbb' => 'bbb',
'ccc' => array(
'ddd' => 'ddd'
)
));
var_dump( check($data, 'aaa.bbb') ); // true
var_dump( check($data, 'aaa.bbb', 'aaa.ccc') ); // true
var_dump( check($data, 'zzz') ); // false
var_dump( check($data, 'aaa.bbb', 'zzz') ); // false
var_dump( get_value($data, 'aaa.bbb', 'default value') ); // "bbb"
var_dump( get_value($data, 'zzz', 'default value') ); // "default value"