I have a multidimensional array that could be any size or depth. I'm basically trying replace empty values with a value but only in certain cases. Here is an example of the array, it's quite large but I want to illustrate my point well:
[field_ter] =>
[field_title] => Array
(
[0] => Array
(
[value] =>
)
)
[field_firstnames] => Array
(
[0] => Array
(
[value] => test9
)
)
[field_birth] => Array
(
[0] => Array
(
[value] =>
)
)
[field_postal] => Array
(
[0] => Array
(
[value] =>
)
)
[group_certificates] => Array
(
[0] => Array
(
[_delta] => 0
[field_cert_details] => Array
(
[value] =>
)
[field_cert_issuedate] => Array
(
[value] => Array
(
[date] =>
)
)
[field_cert_expiry] => Array
(
[value] => Array
(
[date] =>
)
)
[field_cert_issue_country] => Array
(
[value] =>
)
[field_cert_limits] => Array
(
[value] =>
)
)
[1] => Array
(
[_delta] => 1
[field_cert_details] => Array
(
[value] =>
)
[field_cert_issuedate] => Array
(
[value] => Array
(
[date] =>
)
)
[field_cert_expiry] => Array
(
[value] => Array
(
[date] =>
)
)
[field_cert_issue_country] => Array
(
[value] =>
)
[field_cert_limits] => Array
(
[value] =>
)
)
)
What I'm trying to do is find any element in the array that is empty, then replace the empty value with a value. I have an array of exceptions where the empty element is not replaced. This is the function I'm working on at the moment:
function check_empty(&$array) {
$exceptions = array('changed', 'form_build_id','date', 'status', 'op');
// This is the array we will return at the end of the function
$new_array = array();
foreach($array as $key => $value) {
if(is_array($value)) {
check_empty($value);
}
elseif ($value == '' && !in_array($key, $exceptions)) {
$new_array[$key] = '$$$';
}
else {
$new_array[$key] = $value;
}
}
return $new_array;
}
Could someone help me tweak my function or point me in the direction of a better way? I tried array_walk_recursive but it doesn't work with my arrays.
You need to assign the return value of the recursive check_empty:
function check_empty($array) {
$exceptions = array('changed', 'form_build_id','date', 'status', 'op');
// This is the array we will return at the end of the function
$new_array = array();
foreach ($array as $key => $value) {
if (is_array($value)) {
$new_array[$key] = check_empty($value);
}
elseif ($value == '' && !in_array($key, $exceptions)) {
$new_array[$key] = '$$$';
}
else {
$new_array[$key] = $value;
}
}
return $new_array;
}
if(is_array($value)) {
check_empty($value);
}
Here you don't return resulting value to anywhere. Probably that's the problem
Related
I have a multidimensional associative array which has a set of array. I want to change my array index value from some array value.
I already tried some array functions but my array also contains some null array so laravel function keyBy not give me wanted result.
$arr1=array(0 =>array(),1=>array(0=>array('quan'=>10,'handle' => 'baroque'),1 =>array('quan'=>20,'handle' => 'baroque')),
2 =>array (0 =>array('quan' => 5,'handle' => 'adidas')));
My expected result array must be like this
$arr2=array(0 =>array(),'baroque'=>array(0=>array('quan'=>10,'handle' => 'baroque'),1 =>array('quan'=>20,'handle' => 'baroque')),
'adidas' =>array (0 =>array('quan' => 5,'handle' => 'adidas')));
You can use the classic foreach. Check if the handle on element 0 exists using isset, if it does, use that as the key.
$arr1 = //...
$result = array();
foreach($arr1 as $key => $val) {
if (is_array($val) && isset($val[0]["handle"])) $result[ $val[0]["handle"] ] = $val;
else $result[$key] = $val;
}
$result will be:
Array
(
[0] => Array
(
)
[baroque] => Array
(
[0] => Array
(
[quan] => 10
[handle] => baroque
)
[1] => Array
(
[quan] => 20
[handle] => baroque
)
)
[adidas] => Array
(
[0] => Array
(
[quan] => 5
[handle] => adidas
)
)
)
You can use without condition by grouping at the handle as key directly.
$result = [];
foreach ($arr as $key => $value) {
if (!empty($value)) {
foreach ($value as $key1 => $value1) {
$result[$value1['handle']][] = $value1;
}
} else {
$result[] = $value;
}
}
Demo
Output:-
Array
(
[0] => Array
(
)
[baroque] => Array
(
[0] => Array
(
[quan] => 10
[handle] => baroque
)
[1] => Array
(
[quan] => 20
[handle] => baroque
)
)
[adidas] => Array
(
[0] => Array
(
[quan] => 5
[handle] => adidas
)
)
)
Try this..
$res = [];
foreach($x as $key => $value)
{
if(empty($value))
{
$res[] = $value;
}
else
{
foreach($value as $v => $k)
{
if(array_key_exists($k['handle'],$res))
{
$res[$k['handle']][] = ['quan' => $k['quan'],'handle' => $k['handle']];
}
else
{
$res[$k['handle']][0] = ['quan' => $k['quan'],'handle' => $k['handle']];
}
}
}
}
The result is going to be like this.
Array
(
[0] => Array
(
)
[baroque] => Array
(
[0] => Array
(
[quan] => 10
[handle] => baroque
)
[1] => Array
(
[quan] => 20
[handle] => baroque
)
)
[adidas] => Array
(
[0] => Array
(
[quan] => 5
[handle] => adidas
)
)
)
I have an array, when i tried to print_r was just like this :
Array ( [user_id] => Erick ) Array ( [user_id] => Baldi) Array([user_id]=> Bintang ) Array ( [user_id] => Bagas ) Array ( [user_id] => Baim )
My Expected output just like :
Array (
Array (
[user_id] => Erick
)
Array (
[user_id] => Baldi
)
Array (
[user_id] => Bintang
)
Array (
[user_id] => Bagas
)
Array (
[user_id] => Baim
)
)
Anyone here have an idea ? I'm stuck with this.
This my php code :
public function get_userid() {
// $action = $this->input->post('action');
$customerField = $this->input->post('customer');
$projectField = $this->input->post('project');
$user_roleField = $this->input->post('role');
for ($i=0; $i<count($customerField); $i++) {
for ($j=0; $j<count($projectField); $j++) {
for ($k=0; $k<count($user_roleField); $k++) {
array_push($test, $this->get_array_push($customerField[$i], $projectField[$j], $user_roleField[$k]));
}
}
}
}
public function get_array_push($customer, $project, $user_role) {
$query = $this->db->query("SELECT user_id
FROM `ixt_user_project_list`
LEFT JOIN ixt_user_type ON ixt_user_project_list.user_type = ixt_user_type.user_type
WHERE ixt_user_project_list.user_cust_id ='".$customer."'
AND ixt_user_project_list.user_project_id ='".$project."'
AND ixt_user_type.user_owner ='".$user_role."'")->result_array();
//Filter null array
foreach ($query as $key => $value) {
print_r($value);
}
}
And this is my initial query value :
Array ( [0] => Array ( [user_id] => Erick ) ) Array ( ) Array ( ) Array ( ) Array ( ) Array ( ) Array ( [0] => Array ( [user_id] => Baldi ) [1] => Array ( [user_id] => Bintang ) ) Array ( [0] => Array ( [user_id] => Bagas ) [1] => Array ( [user_id] => Baim ) )
As #scaisEdge wrote - its happening because you use the print_r inside the foreach loop.
If you want to filter null result you can use array-filter as:
$arr = array(array("user_id" => "aaa"), null, array(), array("user_id" => null), array("otherField" => "bbb"));
$filterdResult = array_filter($arr, function($elem) {
return ($elem && array_key_exists("user_id", $elem) && !is_null($elem["user_id"]));
});
Now you can just do print_r($filterdResult );
This will output:
Array
(
[0] => Array
(
[user_id] => aaa
)
)
Edited: After setting your new input as:
$query = array(array(array("user_id" => "aaa"), null, array(), array("user_id" => null)), array(array("user_id" => "ccc"), null, array(),array("user_id" =>"ddd")));
You can use the following:
$res = array();
//Filter null array
foreach ($query as $key => $value) {
array_push($res, array_filter($value, function($elem) {
return ($elem && array_key_exists("user_id", $elem) && !is_null($elem["user_id"])); }));
}
print_r($res);
Which output:
Array
(
[0] => Array
(
[0] => Array
(
[user_id] => aaa
)
)
[1] => Array
(
[0] => Array
(
[user_id] => ccc
)
[3] => Array
(
[user_id] => ddd
)
)
)
From here flatten is available if needed.
#David Winder I tried to combine as your suggesstion with the null array filter.
$res = array();
//Filter null array
foreach ($query as $key => $value) {
if (!is_null($value)) {
$res[] = $value;
//print_r($res);
}
}
But when i print_r($res) inside the foreach loop the result became duplicate array inside all of the array value.
I have array like this
Array
(
[0] => Array
(
[text] => 1
)
[1] => Array
(
[0] => Array
(
[text] => 2
)
[1] => Array
(
[0] => Array
(
[text] => 3
)
)
[2] => Array
(
[text] => 4
)
)
[2] => Array
(
[text] => 5
)
)
i dont know number of dimensions, there can be many of them. Also key of target subarrays can be not 'text', but its always text key, not numerical. How do i turn this array into array like this?
Array
(
[0] => Array
(
[text] => 1
)
[1] => Array
(
[text] => 2
)
[2] => Array
(
[text] => 3
)
[3] => Array
(
[text] => 4
)
[4] => Array
(
[text] => 5
)
)
UPDATE: Okay, i didnt explain, and didnt understand whole question by myself. The thing is that array is formed by recursion i have one function:
public static function goToAction($action)
{
$actions = array();
$logic = file_get_contents('../../logic/logic.json');
$logic_array = json_decode($logic, true);
unset($logic);
if (!isset($logic_array[$action])) {
return false;
} else {
foreach ($logic_array[$action] as $action) {
$actions[] = self::parseActionType($action);
}
}
return $actions;
}
and then my array ($data) is forming here
public static function parseActionType($actions)
{
$data = array();
foreach ($actions as $key => $action) {
switch ($key) {
case 'goto': {
$goto_actions = self::goToAction($action);
foreach ($goto_actions as $goto_action) {
$data[]= $goto_action;
}
} break;
....
}
}
so these functions can call each other, and there can be recursion, and as I understood when this happens, this code $data[] = $goto_action puts all of received actions in one element, but I need to put each $goto_action in differend element of $data array
You can use array_walk_recursive to traverse all the value. live demo
$result = [];
array_walk_recursive($array, function($v, $k) use(&$result){
$result[] = [$k => $v];
});
I need to check if the value exists in the array and once it exists I need to get the object.
Array
(
[0] => Array
(
[_id] => Array
(
[purok] => test
[year] => 2017
[options] => below-1
)
[data] => Array
(
[58cf4935572d6e32900057ab] => Array
(
[age-sex-distribution] => Array
(
[age-range] => Array
(
[options] => below-1
)
[gender] => Array
(
[male-distribution-count] => 12
[female-distribution-count] => 12
)
)
)
)
[date] => 2017-07-08
)
[1] => Array
(
[_id] => Array
(
[purok] => test
[year] => 2017
[options] => toddlers (1-2)
)
[data] => Array
(
[58cf4935572d6e32900057ab12] => Array
(
[age-sex-distribution] => Array
(
[age-range] => Array
(
[options] => toddlers (1-2)
)
[gender] => Array
(
[male-distribution-count] => 12
[female-distribution-count] => 12
)
)
)
)
[date] => 2017-07-08
)
)
I need to check this [options] => below-1 if it exists. One it exist, I need to get the data in the array.
So far, I have tried this one.
$keySearch = "data.options";
$dataOption = array_search("below-1", array_column($rec, $keySearch));
print_r($dataOption);
But got no result.
Thanks for helping me in advance.
$temp = [];
for ($data as $value){
if($value['_id']['options'] == 'below-1'){
$temp[] = $value;
}
}
print_r($temp);
you can try this
Try this:
function search_array($needle, $haystack) {
if(in_array($needle, $haystack)) {
return true;
}
foreach($haystack as $element) {
if(is_array($element) && search_array($needle, $element))
return true;
}
return false;
}
if(!search_array($value, $array)) {
// do something if the given value does not exist in the array
}else{
// do something if the given value exists in the array
}
you should try this :
for($i=0; $i < count($rec); $i++) {
if ($rec[$i]['_id']['options'] === "below-1") {
$dataOption = $rec[$i]['data'];
break;
}
}
print_r($dataOption);
It should do what you expect ;-)
i have an array $mainArray of arrays and i would like to remove / undset the arrays that vave keys with no value.
here is my array:
Array
(
[0] => Array
(
[msg_id] => 203
[comment] => Array
(
[0] => Array
(
[com_id] =>
)
)
)
[1] => Array
(
[msg_id] => 202
[comment] => Array
(
[0] => Array
(
[com_id] => 196
)
[1] => Array
(
[com_id] => 197
)
[2] => Array
(
[com_id] =>
)
)
)
[2] => Array
(
[msg_id] => 201
[comment] => Array
(
[0] => Array
(
[com_id] => 198
)
[1] => Array
(
[com_id] =>
)
)
)
)
In this case i would like to look inside comment array arrays and see if there are any of them that have empty values. The best case scenario would be to remove the comment array entirely if all sub arrays are empty.
nut im of with leaving the comment hey there just null
this array should become:
Array
(
[0] => Array
(
[msg_id] => 203
)
[1] => Array
(
[msg_id] => 202
[comment] => Array
(
[0] => Array
(
[com_id] => 196
)
[1] => Array
(
[com_id] => 197
)
)
)
[2] => Array
(
[msg_id] => 201
)
)
any ideas on how to proceed?
thanks.
array_filter() is what you're after. Particularly a recursive version. The following was taken from a comment on the PHP Doc:.
function array_filter_recursive($array, $callback = null) {
foreach ($array as $key => & $value) {
if (is_array($value)) {
$value = array_filter_recursive($value, $callback);
}
else {
if ( ! is_null($callback)) {
if ( ! $callback($value)) {
unset($array[$key]);
}
}
else {
if ( ! (bool) $value) {
unset($array[$key]);
}
}
}
}
unset($value);
return $array;
}
Use php's unset() to unset any array key/value.
More info on this link http://in3.php.net/unset
in your case the code can be, (i have not tested it. but let me know if you have any problem and i can fix it)
function unsetCommentFromArray($mainArray) {
foreach($mainArray as $key => $value) {
foreach($value['comment'] as $k => $v) {
if(empty($v['com_id'])) {
unset($mainArray[$key]['comment'][$k]);
}
}
}
return $mainArray;
}
$array = array_map(function ($i) {
$i['comment'] = array_filter($i['comment'], function ($c) { return $c['com_id']; });
return array_filter($i);
}, $array);
Requires PHP 5.3 or higher.