I have tried all the solutions suggested in this post but have not been able to make them work in my case.
My array :
array(2) {
["number_s"]=>
array(14) {
[0]=>
string(2) "22"
[1]=>
string(2) "23"
[2]=>
string(0) ""
[3]=>
string(0) ""
[4]=>
string(0) ""
}
["player_name"]=>
array(14) {
[0]=>
string(9) "John Doe"
[1]=>
string(11) "Jack Sparrow"
[2]=>
string(0) ""
[3]=>
string(0) ""
[4]=>
string(0) ""
}
}
I would like to remove all the empty entries but how to do that ?
Thanks a lot for help
It seems like array_filter for each subarray will do what you want.
$array['number_s'] = array_filter($array['number_s']);
$array['player_name'] = array_filter($array['player_name']);
When called without callback function it just removes all empty entries. See docs for details.
But be aware that it will remove "0" and all values which considered empty.
Assuming there aren't arbitrary numbers of subarrays, you may transverse them (as references) and use unset to remove them from the array:
foreach ($array as &$subarray) {
foreach ($subarray as $key => $value) {
if (empty($value)) {
unset($subarray[$key]);
}
}
}
It's simpler with a functional approach:
$array = array_map(
fn($subarray) => array_filter($subarray),
$array
);
If the array may have arbitrary levels, you may implement a recursive function:
function remove_empty_recursive(array &$array)
{
foreach($array as $key => &$value) {
if (empty($value)) {
unset($array[$key]);
} elseif (is_array($value)) {
remove_empty_recursive($value);
}
}
}
Notice all those solutions assume you want to remove "0", 0 and false from the array. Otherwise, you need to specify another criteria, instead of using empty. For instance:
$array = array_map(
fn($subarray) => array_filter(
$subarray,
fn($value) => !empty($value) || is_numeric($value) || $value === false
),
$array
);
Related
I have the variable $request. If i do vardump($request), I get the output of:
array(7) {
["controller"]=> string(5) "index"
["action"]=> string(5)"index"
["module"]=> string(7) "default"
[2]=> array(8) {
["g_goal_list_id"]=> string(3) "127"
["textgoal"]=> string(9) "eats food"
["task_0"]=> string(1) "0"
["value_0"]=> string(5) "pukes"
["task_1"]=> string(1) "0"
["value_1"]=> string(0) ""
["task_2"]=> string(1) "0"
["value_2"]=> string(0) ""
}
[3]=> array(10) {
["g_goal_list_id"]=> string(3) "128"
["textgoal"]=> string(9) "goes home"
["task_0"]=> string(1) "0"
["value_0"]=> string(20) "but never comes back"
["task_1"]=> string(1) "0"
["value_1"]=> string(14) "stays home now"
["task_2"]=> string(1) "0"
["value_2"]=> string(0) ""
["task_3"]=> string(1) "0"
["value_3"]=> string(0) ""
}
["submit"]=> string(4) "Save"
["task"]=> string(1) "5"
}
which is all correct. However, I'm trying to use a foreach statment to grab values from the $request array and put them into a data array, and then submit that to the mysql db...
foreach($request as $currentrow){
//skips row if the field is empty
if(strlen($currentrow['value']) < 1)//need to make sure I've defined $currentrow['value']
continue;//skips row with empty field
//I only need to grab the value/list_id/account_id from the form
$data = array('value' => $currentrow['value'],
'g_goal_list_id' => $currentrow['g_goal_list_id'],
'account_id' => g_getAccountId(),
);
var_dump($data);
However, when I var_dump($data); my output looks like this:
array(3) { ["value"]=> string(1) "i" ["g_goal_list_id"]=> string(1) "i" ["account_id"]=> string(1) "1" }
array(3) { ["value"]=> string(1) "S" ["g_goal_list_id"]=> string(1) "S" ["account_id"]=> string(1) "1" }
array(3) { ["value"]=> string(1) "5" ["g_goal_list_id"]=> string(1) "5" ["account_id"]=> string(1) "1" }
The only thing that is correct in that var_dump($data) is the ["account_id"]
I'm thinking that my loop is incorrect, and I'm pretty bad with loops. Sooooo yeah, hopefully I included enough information. Thank you.
What you need is something like this:
foreach($request as $k=>$currentrow)
{
$hit = false;
$data = array();
// Only look for sub-arrays
if(is_array($currentrow))
{
foreach($currentrow as $k2=>$v2)
{
$explode = explode('_', $k2);
if($explode[0] === 'value') //need to make sure I've defined $currentrow['value'] regardless of suffix
{
$hit = true;
$data = array(
'value' => $v2,
'g_goal_list_id' => $currentrow[$k]['g_goal_list_id'],
'account_id' => g_getAccountId(),
);
continue;
}
}
}
if($hit === false)
{
continue;
}
var_dump($data);
}
This element: $currentrow['values'] does not exist (check your logs, you should see notices). Neither does $currentrow['g_goal_list_id'].
You loop through an array with all different elements, the first being a string, with value index. When you then take that string and subscribe that with values, it throws a warning, but then takes the first element.
To clarify, a some CLI code:
php > $a="abcd";
php > echo $a["foo"];
PHP Warning: Illegal string offset 'foo' in php shell code on line 1
a
If you want to loop over keys and values, do like this:
foreach($request as $key=>$value) {
}
That being said, I think a loop is not what you want, you do not have straighforward table-like data.
Huge thanks to #MonkeyZeus. I kept on getting an array that had the proper keys but all the values were null. Turns out I just needed to put my var_dump($data) inside of my loop, because when it was on the outside it was returning only the last array it looped thorough. On my form the last values it loops through were empty fields, that are meant for the user to add input. Also, I had to change 'g_goal_list_id' => $currentrow[$k]['g_goal_list_id'] to just 'g_goal_list_id' => $currentrow['g_goal_list_id']
foreach ($request as $k=> $currentrow) {
$hit = false;
$data = array();
if(is_array($currentrow)){
foreach ($currentrow as $k2 => $v2) {
$explode = explode('_', $k2); //blows off the suffix of the $key
//var_dump($explode);
//$explode=substr($explode,2);
//echo $k2;
//echo '******';
//echo $v2;
echo $explode[0];
echo '/';
if($explode[0] == 'value'){
//echo "[" . $currentrow['g_goal_list_id'] . "]";
$hit = true;
$data = array(
'value' => $v2,
'g_goal_list_id' => $currentrow['g_goal_list_id'],
'account_id'=> g_getAccountId(),
);
continue;
}
var_dump($data);
}
}
if ($hit === false){
continue;
}
break;
}
I write a multilingual wordpress homepage. I need to load all languages into array, then detect the user language and then depending on user language remove the other languages from the array.
I want to do partial check on array to see if "Title" contains _DE or _ES and then depending on result remove one or the other from array.
So far I have
Data
array(2) {
[1]=> array(3) { ["order"]=> string(1) "1" ["title"]=> string(9) "Slider_ES" ["id"]=> string(3) "500" }
[2]=> array(3) { ["order"]=> string(1) "2" ["title"]=> string(11) "Slider_DE" ["id"]=> string(3) "493" }
}
Logic
$current_language = get_locale(); // Wordpress function which returns either es_ES or de_DE codes
if ($current_language == es-ES) {
foreach ($array as $key => $item) {
if ($item['title'] === '_DE') {
unset($array[$key]);
}
}
} else {
foreach ($array as $key => $item) {
if ($item['title'] === '_ES') {
unset($array[$key]);
}
}
}
What did I miss?
You can use the strpos function which is used to find the occurrence of one string inside other like this:
if (strpos($item['title'],'_DE') !== false) {
unset($array[$key]);
}
I'm receiving a JSON and trying to interpret some values using PHP.
Example snippet from a JSON dump:
["11811"]=>
object(stdClass)#15 (11) {
["parent_area"]=>
NULL
["generation_high"]=>
int(19)
["all_names"]=>
object(stdClass)#16 (0) {
}
["id"]=>
int(11811)
["codes"]=>
object(stdClass)#17 (3) {
["ons"]=>
string(2) "08"
["gss"]=>
string(9) "E15000008"
["unit_id"]=>
string(5) "41421"
}
["name"]=>
string(10) "South East"
["country"]=>
string(1) "E"
["type_name"]=>
string(15) "European region"
["generation_low"]=>
int(1)
["country_name"]=>
string(7) "England"
["type"]=>
string(3) "EUR"
}
As there is lots of (nested) data, I need to obtain the value of ["name"] where ["type_name"] == 'European region'.
Thanks.
You could use array_filter()
$data_array = array(...);
function is_european($data) {
return $data->type_name == 'European region';
}
$filtered = array_filter($data_array,'is_european');
And then use filtered array to obtain values.
Maybe a better way would be to use JsonPath, like this, assuming your array is a result of decoding JSON (object):
$names = jsonPath($data_object, "$.[?(#['type_name'] == 'European region')].name");
Haven't tried this myself, it may need a bit of correction.
Try this:
<?php
$json = JSON_decode(str,true);
$arr = Array();
foreach($json as $f) {
/* eg. $f = $json["11811"] */
if($f['type_name'] == 'European region') {
$arr[] = $f['name'];
}
}
?>
I have an array like the one below, I need to check for duplicates within the multi-dimensional associative array. I don't think that I really need to say much more, I've already tried array_unique and it happens to think things are duplicates when they clearly aren't.
I'm looking to change this:
array(3) {
[1]=>
array(2) {
["itself"]=>
string(31) "New York"
["status"]=>
string(18) "great"
}
[2]=>
array(2) {
["itself"]=>
string(36) "New York"
["status"]=>
string(22) "great"
}
[3]=>
array(2) {
["itself"]=>
string(29) "New York"
["status"]=>
string(18) "great"
}
}
In to this:
array(1) {
[1]=>
array(2) {
["itself"]=>
string(31) "New York"
["status"]=>
string(18) "great"
}
}
Is this an actual output, because the string-lengths don't match... Maybe some hidden data (html-tags, non-printable characters, etc.)?
If not: array_unique wants a string representation:
$result = array_intersect_key(
$input,
array_unique(array_map('serialize',$input)));
$array = array(YOUR ARRAY);
foreach ($array as $key1 => $value1){
foreach ($array as $key2 => $value2){
if($array[$key1] == $array[$key2] && $key1 != $key2){
unset($array[$key1]);
}
}
}
array(3) {
[0]=>
array(4) {
["Field1"]=>
string(8) "80000007"
["Field2"]=>
string(16) "O70000006"
["Field3"]=>
string(0) ""
["Field4"]=>12345
string(0) ""
}
[1]=>
array(4) {
["Field1"]=>
string(8) "80000008"
["Field2"]=>
string(16) "O70000007"
["Field3"]=>
string(0) ""
["Field4"]=>78965
string(0) ""
}
[2]=>
array(4) {
["Field1"]=>
string(8) "80000009"
["Field2"]=>
string(16) "H80000006"
["Field3"]=>
string(0) ""
["Field4"]=>12345
string(0) ""
}
}
I have the above array i want to store this items of array into another temp array and use it . Here is what iam doing
$arr_tmp = array();
foreach ($result['record'] as $key => $value){
$arr_tmp['Field1'] = $value['Field1'];
$arr_tmp['Field2'] = $value['Field2'];
$arr_tmp['Field3'] = $value['Field3'];
$arr_tmp['Field4'] = $value['Field4'];
}
when i do var_dump($arr_tmp). Iam getting only the last record in the array. I need the same result set in this $arr_tmp when using foreach loop so that i can add some more items to this array .
You've only created a single arr_tmp array, and overwrite the values on each loop iteration. Possibly you'd want something like:
$arr_tmp[] = array('Field1' => $value['Field1'], 'Field2' => $value['Field2'], etc...)
inside the loop instead.
But, unless I'm reading your original array wrong, this will simply re-create the original array with new keys, so that begs the question... why? Wouldn't it be easier to just do:
$arr_tmp = $original_array;
?
$arr_tmp = array();
foreach ($result['record'] as $key => $value){
$cur = array();
$cur['Field1'] = $value['Field1'];
$cur['Field2'] = $value['Field2'];
$cur['Field3'] = $value['Field3'];
$cur['Field4'] = $value['Field4'];
$arr_tmp[] = $cur;
}