How to remove the empty entity from an array - php

I have a function, which returns back the array. But the way I form this array is by "explode"ing a string. And when I do that, I get an extra empty string.
So now my issue is that I dont want to return the empty array entity.
My function code is shown below:
public function purge_file($keys)
{
if(empty($keys))
throw new C7_Exception('Missing/Bad arguments');
$lib_tools_storage = new C7_Lib_Tools_Storage();
$file_ids = explode(";",$keys);
foreach($file_ids as $key)
{
//echo "this is file_id = $key ";
if(!empty($key))
$lib_tools_storage->purge_file($key);
}
return array('result_code' => 0,
'data' => array('keys' => $file_ids)
);
}

You can trim the outer semicolons before passing to explode:
$keys = '1;2;3;4;';
$file_ids = explode(";", trim($keys, ';'));
print_r($file_ids);
/* output
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
)
*/

public function purge_file($keys)
{
if(empty($keys))
throw new C7_Exception('Missing/Bad arguments');
$lib_tools_storage = new C7_Lib_Tools_Storage();
$file_ids = explode(";",$keys);
foreach($file_ids as $key)
{
//echo "this is file_id = $key ";
if(!empty($key))
$lib_tools_storage->purge_file($key);
}
foreach($file_ids as $key)
{
if (!empty($key))
{
$keys_new[] = $key;
}
}
return array('result_code' => 0,
'data' => array('keys' => $keys_new)
);
}

use this function array_filter(explode(",", $params['emails']));.

Related

Trouble renaming array key in PHP [duplicate]

This question already has answers here:
PHP rename array keys in multidimensional array
(10 answers)
Closed last month.
When I var_dump on a variable called $tags (a multidimensional array) I get this:
Array
(
[0] => Array
(
[name] => tabbing
[url] => tabbing
)
[1] => Array
(
[name] => tabby ridiman
[url] => tabby-ridiman
)
[2] => Array
(
[name] => tables
[url] => tables
)
[3] => Array
(
[name] => tabloids
[url] => tabloids
)
[4] => Array
(
[name] => taco bell
[url] => taco-bell
)
[5] => Array
(
[name] => tacos
[url] => tacos
)
)
I would like to rename all array keys called "url" to be called "value". What would be a good way to do this?
You could use array_map() to do it.
$tags = array_map(function($tag) {
return array(
'name' => $tag['name'],
'value' => $tag['url']
);
}, $tags);
Loop through, set new key, unset old key.
foreach($tags as &$val){
$val['value'] = $val['url'];
unset($val['url']);
}
Talking about functional PHP, I have this more generic answer:
array_map(function($arr){
$ret = $arr;
$ret['value'] = $ret['url'];
unset($ret['url']);
return $ret;
}, $tag);
}
Recursive php rename keys function:
function replaceKeys($oldKey, $newKey, array $input){
$return = array();
foreach ($input as $key => $value) {
if ($key===$oldKey)
$key = $newKey;
if (is_array($value))
$value = replaceKeys( $oldKey, $newKey, $value);
$return[$key] = $value;
}
return $return;
}
foreach ($basearr as &$row)
{
$row['value'] = $row['url'];
unset( $row['url'] );
}
unset($row);
This should work in most versions of PHP 4+. Array map using anonymous functions is not supported below 5.3.
Also the foreach examples will throw a warning when using strict PHP error handling.
Here is a small multi-dimensional key renaming function. It can also be used to process arrays to have the correct keys for integrity throughout your app. It will not throw any errors when a key does not exist.
function multi_rename_key(&$array, $old_keys, $new_keys)
{
if(!is_array($array)){
($array=="") ? $array=array() : false;
return $array;
}
foreach($array as &$arr){
if (is_array($old_keys))
{
foreach($new_keys as $k => $new_key)
{
(isset($old_keys[$k])) ? true : $old_keys[$k]=NULL;
$arr[$new_key] = (isset($arr[$old_keys[$k]]) ? $arr[$old_keys[$k]] : null);
unset($arr[$old_keys[$k]]);
}
}else{
$arr[$new_keys] = (isset($arr[$old_keys]) ? $arr[$old_keys] : null);
unset($arr[$old_keys]);
}
}
return $array;
}
Usage is simple. You can either change a single key like in your example:
multi_rename_key($tags, "url", "value");
or a more complex multikey
multi_rename_key($tags, array("url","name"), array("value","title"));
It uses similar syntax as preg_replace() where the amount of $old_keys and $new_keys should be the same. However when they are not a blank key is added. This means you can use it to add a sort if schema to your array.
Use this all the time, hope it helps!
Very simple approach to replace keys in a multidimensional array, and maybe even a bit dangerous, but should work fine if you have some kind of control over the source array:
$array = [ 'oldkey' => [ 'oldkey' => 'wow'] ];
$new_array = json_decode(str_replace('"oldkey":', '"newkey":', json_encode($array)));
print_r($new_array); // [ 'newkey' => [ 'newkey' => 'wow'] ]
This doesn't have to be difficult in the least. You can simply assign the arrays around regardless of how deep they are in a multi-dimensional array:
$array['key_old'] = $array['key_new'];
unset($array['key_old']);
You can do it without any loop
Like below
$tags = str_replace("url", "value", json_encode($tags));
$tags = json_decode($tags, true);
class DataHelper{
private static function __renameArrayKeysRecursive($map = [], &$array = [], $level = 0, &$storage = []) {
foreach ($map as $old => $new) {
$old = preg_replace('/([\.]{1}+)$/', '', trim($old));
if ($new) {
if (!is_array($new)) {
$array[$new] = $array[$old];
$storage[$level][$old] = $new;
unset($array[$old]);
} else {
if (isset($array[$old])) {
static::__renameArrayKeysRecursive($new, $array[$old], $level + 1, $storage);
} else if (isset($array[$storage[$level][$old]])) {
static::__renameArrayKeysRecursive($new, $array[$storage[$level][$old]], $level + 1, $storage);
}
}
}
}
}
/**
* Renames array keys. (add "." at the end of key in mapping array if you want rename multidimentional array key).
* #param type $map
* #param type $array
*/
public static function renameArrayKeys($map = [], &$array = [])
{
$storage = [];
static::__renameArrayKeysRecursive($map, $array, 0, $storage);
unset($storage);
}
}
Use:
DataHelper::renameArrayKeys([
'a' => 'b',
'abc.' => [
'abcd' => 'dcba'
]
], $yourArray);
It is from duplicated question
$json = '[
{"product_id":"63","product_batch":"BAtch1","product_quantity":"50","product_price":"200","discount":"0","net_price":"20000"},
{"product_id":"67","product_batch":"Batch2","product_quantity":"50","product_price":"200","discount":"0","net_price":"20000"}
]';
$array = json_decode($json, true);
$out = array_map(function ($product) {
return array_merge([
'price' => $product['product_price'],
'quantity' => $product['product_quantity'],
], array_flip(array_filter(array_flip($product), function ($value) {
return $value != 'product_price' && $value != 'product_quantity';
})));
}, $array);
var_dump($out);
https://repl.it/#Piterden/Replace-keys-in-array
This is how I rename keys, especially with data that has been uploaded in a spreadsheet:
function changeKeys($array, $new_keys) {
$newArray = [];
foreach($array as $row) {
$oldKeys = array_keys($row);
$indexedRow = [];
foreach($new_keys as $index => $newKey)
$indexedRow[$newKey] = isset($oldKeys[$index]) ? $row[$oldKeys[$index]] : '';
$newArray[] = $indexedRow;
}
return $newArray;
}
Based on the great solution provided by Alex, I created a little more flexible solution based on a scenario I was dealing with. So now you can use the same function for multiple arrays with different numbers of nested key pairs, you just need to pass in an array of key names to use as replacements.
$data_arr = [
0 => ['46894', 'SS'],
1 => ['46855', 'AZ'],
];
function renameKeys(&$data_arr, $columnNames) {
// change key names to be easier to work with.
$data_arr = array_map(function($tag) use( $columnNames) {
$tempArray = [];
$foreachindex = 0;
foreach ($tag as $key => $item) {
$tempArray[$columnNames[$foreachindex]] = $item;
$foreachindex++;
}
return $tempArray;
}, $data_arr);
}
renameKeys($data_arr, ["STRATEGY_ID","DATA_SOURCE"]);
this work perfectly for me
$some_options = array();;
if( !empty( $some_options ) ) {
foreach( $some_options as $theme_options_key => $theme_options_value ) {
if (strpos( $theme_options_key,'abc') !== false) { //first we check if the value contain
$theme_options_new_key = str_replace( 'abc', 'xyz', $theme_options_key ); //if yes, we simply replace
unset( $some_options[$theme_options_key] );
$some_options[$theme_options_new_key] = $theme_options_value;
}
}
}
return $some_options;

How to merge array multi key to single array

I have a array multi level
$array = array("14529" => array("900" => array("87" => array() ) ) );
print_r(array_keys($array)); // result array("14529");
How to merge this array to single array
$array = array("14529", "900", "87");
Here is a function that does what you want. It is done recursively, so it doesn't matter how deep the array is.
function mergeArrayMultiKeyToSingleArray($array, $result=[])
{
foreach($array as $key => $value) {
$result[] = $key;
if(is_array($value)) {
$result = mergeArrayMultiKeyToSingleArray($value, $result);
}
}
return $result;
}
// USAGE:
$array = array("14529" => array("900" => array("87" => array() ) ) );
$array = mergeArrayMultiKeyToSingleArray($array);
// $array is now ["14529", "900", "87"]
The solution using RecursiveIteratorIterator class:
$arr = ["14529" => ["900" => ["87" => [] ] ] ];
$keys = [];
foreach (new RecursiveIteratorIterator(new RecursiveArrayIterator($arr), RecursiveIteratorIterator::SELF_FIRST) as $k => $v) {
$keys[] = $k;
}
print_r($keys);
The output:
Array
(
[0] => 14529
[1] => 900
[2] => 87
)
I did this using class
class ArrayStripper
{
private $items = [];
public function strip($arrayOrItem)
{
if(is_array($arrayOrItem))
{
foreach ($arrayOrItem as $item)
{
$this->strip($item);
}
}
else
{
$this->items[] = $arrayOrItem;
}
}
public function get()
{
return $this->items;
}
}
$array = [1 , [2,3] , 4 , [[5 , 6 , 7] , [8 ,9] , 10]];
$stripper = new ArrayStripper();
$stripper->strip($array);
var_dump($stripper->get());

Is there something like keypath in an associative array in PHP?

I want to dissect an array like this:
[
"ID",
"UUID",
"pushNotifications.sent",
"campaigns.boundDate",
"campaigns.endDate",
"campaigns.pushMessages.sentDate",
"pushNotifications.tapped"
]
To a format like this:
{
"ID" : 1,
"UUID" : 1,
"pushNotifications" :
{
"sent" : 1,
"tapped" : 1
},
"campaigns" :
{
"boundDate" : 1,
"endDate" : 1,
"pushMessages" :
{
"endDate" : 1
}
}
}
It would be great if I could just set a value on an associative array in a keypath-like manner:
//To achieve this:
$dissected['campaigns']['pushMessages']['sentDate'] = 1;
//By something like this:
$keypath = 'campaigns.pushMessages.sentDate';
$dissected{$keypath} = 1;
How to do this in PHP?
You can use :
$array = [
"ID",
"UUID",
"pushNotifications.sent",
"campaigns.boundDate",
"campaigns.endDate",
"campaigns.pushMessages.sentDate",
"pushNotifications.tapped"
];
// Build Data
$data = array();
foreach($array as $v) {
setValue($data, $v, 1);
}
// Get Value
echo getValue($data, "campaigns.pushMessages.sentDate"); // output 1
Function Used
function setValue(array &$data, $path, $value) {
$temp = &$data;
foreach(explode(".", $path) as $key) {
$temp = &$temp[$key];
}
$temp = $value;
}
function getValue($data, $path) {
$temp = $data;
foreach(explode(".", $path) as $ndx) {
$temp = isset($temp[$ndx]) ? $temp[$ndx] : null;
}
return $temp;
}
function keyset(&$arr, $keypath, $value = NULL)
{
$keys = explode('.', $keypath);
$current = &$arr;
while(count($keys))
{
$key = array_shift($keys);
if(!isset($current[$key]) && count($keys))
{
$current[$key] = array();
}
if(count($keys))
{
$current = &$current[$key];
}
}
$current[$key] = $value;
}
function keyget($arr, $keypath)
{
$keys = explode('.', $keypath);
$current = $arr;
foreach($keys as $key)
{
if(!isset($current[$key]))
{
return NULL;
}
$current = $current[$key];
}
return $current;
}
//Testing code:
$r = array();
header('content-type: text/plain; charset-utf8');
keyset($r, 'this.is.path', 39);
echo keyget($r, 'this.is.path');
var_dump($r);
It's a little rough, I can't guarantee it functions 100%.
Edit: At first you'd be tempted to try to use variable variables, but I've tried that in the past and it doesn't work, so you have to use functions to do it. This works with some limited tests. (And I just added a minor edit to remove an unnecessary array assignment.)
In the meanwhile, I came up with (another) solution:
private function setValueForKeyPath(&$array, $value, $keyPath)
{
$keys = explode(".", $keyPath, 2);
$firstKey = $keys[0];
$remainingKeys = (count($keys) == 2) ? $keys[1] : null;
$isLeaf = ($remainingKeys == null);
if ($isLeaf)
$array[$firstKey] = $value;
else
$this->setValueForKeyPath($array[$firstKey], $value, $remainingKeys);
}
Sorry for the "long" namings, I came from the Objective-C world. :)
So calling this on each keyPath, it actually gives me the output:
fields
Array
(
[0] => ID
[1] => UUID
[2] => pushNotifications.sent
[3] => campaigns.boundDate
[4] => campaigns.endDate
[5] => campaigns.pushMessages.endDate
[6] => pushNotifications.tapped
)
dissectedFields
Array
(
[ID] => 1
[UUID] => 1
[pushNotifications] => Array
(
[sent] => 1
[tapped] => 1
)
[campaigns] => Array
(
[boundDate] => 1
[endDate] => 1
[pushMessages] => Array
(
[endDate] => 1
)
)
)

Find one string and get related values

I have several strings, how can I search the first value and get other values from it?
print_r or ?:
Array( [0] => Title,11,11 [1] => Would,22,22 [2] => Post,55,55 [3] => Ask,66,66 )
like:
If send for this array value Title and getting values Title,11,11
Or send Would getting values Would,22,22
Or send Post getting values Post,55,55
Or send Ask getting values Ask,66,66
How can do it?
Loop over the array with foreach and match the value with strpos.
suppose:
$arr = Array( [0] => Title,11,11 [1] => Would,22,22 [2] => Post,55,55 [3] => Ask,66,66 )
$string = 'Would';
then
//Call the function with the search value in $string and the actual array
$required_arr[$string] = search_my_array($string, $arr);
function($str , $array)
{
//Trace the complete array
for($i = 0; $i<count($array); $i++)
{
//Break the array using explode function based on ','
$arr_values[$i] = explode(',',$array[i])
if($str == $arr_values[$i][0]) // Match the First String with the required string
{
//On match return the array with the values contained in it
return array($arr_values[$i][1], $arr_values[$i][2]);
}
}
}
Now
$required_arr['Would'] // will hold Array([0] => 22 [1] => 22)
Write a function to search the array. This should work well enough
<?php
// test array
$arr = array('Title,11,11','Would,22,22','Post,55,55','Ask,66,66');
// define search function that you pass an array and a search string to
function search($needle,$haystack){
// loop over each passed in array element
foreach($haystack as $v){
// if there is a match at the first position
if(strpos($v,$needle) === 0)
// return the current array element
return $v;
}
// otherwise retur false if not found
return false;
}
// test the function
echo search("Would",$arr);
?>
are the indices important ? why not ..
$arr = array(
'Title' => array(11, 11),
'Would' => array(22, 22),
'Post' => array(55, 55),
'Ask' => array(66,66)
);
$send = "Title"; // for example
$result = $arr[$send];
How about using something like, so you don't loop trough entire array:
$array = array( "Title,11,11", "Would,22,22", "Post,55,55", "Ask,66,66" );
$key = my_array_search('Would', $array);
$getvalues = explode(",", $array[$key]);
function my_array_search($needle = null, $haystack_array = null, $skip = 0)
{
if($needle == null || $haystack_array == null)
die('$needle and $haystack_array are mandatory for function my_array_search()');
foreach($haystack_array as $key => $eval)
{
if($skip != 0)$eval = substr($eval, $skip);
if(stristr($eval, $needle) !== false) return $key;
}
return false;
}

How to modify output of certain function of File_CSV_DataSource?

The following function is from a PEAR script called File_CSV_DataSource, and is a CSV parser.
CSV file is this:
name,age,skill
john,13,knows magic
tanaka,8,makes sushi
jose,5,dances salsa
The current output of this function is like this:
array (0 => array ('name' => 'john','age' => '13','skill' => 'knows magic',),1 =>array('name' => 'tanaka','age' => '8','skill' => 'makes sushi',),2 =>array ('name' => 'jose','age' => '5','skill' => 'dances salsa',),)
what I'm trying to achieve is to make the function to output like this:
array (array ('john','13','knows magic'), array('tanaka','8','makes sushi'), array ( 'jose','5','dances salsa'),)
so without the 0 => and without the column header => , only the value of the cells
Is there any way for me to modify the function bellow to make it output as in my example above?
public function connect($columns = array())
{
if (!$this->isSymmetric()) {
return array();
}
if (!is_array($columns)) {
return array();
}
if ($columns === array()) {
$columns = $this->headers;
}
$ret_arr = array();
foreach ($this->rows as $record) {
$item_array = array();
foreach ($record as $column => $value) {
$header = $this->headers[$column];
if (in_array($header, $columns)) {
$item_array[$header] = $value;
}
}
// do not append empty results
if ($item_array !== array()) {
array_push($ret_arr, $item_array);
}
}
return $ret_arr;
}
Thanks in advance
Just use the built in filegetcsv. It will do that for you.

Categories