Is it possible to remove only the associative array who have all values empty?
Data source:
Array
(
[0] => Array
(
[name] => foo
[phone] => 012345
[email] =>
)
[1] => Array
(
[name] => bar
[phone] =>
[email] => yahoo.com
)
[2] => Array
(
[name] =>
[phone] =>
[email] =>
)
)
Desired output:
Array
(
[0] => Array
(
[name] => foo
[phone] => 012345
[email] =>
)
[1] => Array
(
[name] => bar
[phone] =>
[email] => yahoo.com
)
)
I tried this, but unfortunately I will delete all empty values of arrays
$_arr = array_filter(array_map('array_filter', $_arr));
Array
(
[0] => Array
(
[name] => foo
[phone] => 012345
)
[1] => Array
(
[name] => bar
[email] => yahoo.com
)
)
How could I do it? Thank You
Maybe a slicker way, but:
$array = array_filter($array, function($a) { return array_filter($a); });
Since array_filter is using a true or false return to filter; the array_filter in the function is returning either an empty array evaluated as false, or a non-empty array evaluated as true, and the main array_filter is filtering based upon that.
<?php
$collection = array(
"0" => array
(
'name' => "foo",
'phone' => "012345",
'email' => ''
),
"1" => array
(
'name' => "bar",
'phone' => '',
'email' => "yahoo.com",
),
"2" => array
(
'name' => '',
'phone' => '',
'email' => ''
)
);
foreach($collection as $key=> $entry){
if(count(array_filter($entry)) == 0){
unset($collection[$key]);
}
}
print_r($collection);
Related
stdClass Object (
[id] => 8586332
[email] => hello#myemail.com
[optInType] => Unknown
[emailType] => Html
[dataFields] => Array
(
[0] => stdClass Object ( [key] => FIRSTNAME [value] => Bill )
[1] => stdClass Object ( [key] => FULLNAME [value] => Bill Jones )
[2] => stdClass Object ( [key] => GENDER [value] => )
[3] => stdClass Object ( [key] => LASTNAME [value] => Jones )
[4] => stdClass Object ( [key] => LASTSUBSCRIBED [value] => 2019-12-20T21:13:20.359947Z )
[5] => stdClass Object ( [key] => POSTCODE [value] => )
[6] => stdClass Object ( [key] => THIS_KEY [value] => This Value )
)
[status] => Subscribed )
I have this JSON object and array in PHP that I have decoded.
I am trying to access 'This Value' but I am stuck.
I also need to find a way to do it where I don't know if it will always be number 6.
I have made these attempts:
$object->{"dataFields[1]"};
and
$object['dataFields'][6]['THIS_KEY'];
I can access the email like this:
echo $objec[1]->email;
You will need to search through the subarray for the qualifying object using the key property's value.
There will be functional techniques to do this, but I'll show a simple loop and break technique.
Code: (Demo)
$object = (object) [
'id'=> 8586332,
'email' => 'hello#myemail.com',
'optInType' => 'Unknown',
'emailType' => 'Html',
'dataFields' => [
(object)['key' => 'FIRSTNAME', 'value' => 'Bill'],
(object)['key' => 'FULLNAME', 'value' => 'Tom Jones'],
(object)['key' => 'GENDER', 'value' => ''],
(object)['key' => 'LASTNAME', 'value' => 'Jones'],
(object)['key' => 'LASTSUBSCRIBED', 'value' => '2019-12-20T21:13:20.359947Z'],
(object)['key' => 'POSTCODE', 'value' => ''],
(object)['key' => 'THIS_KEY', 'value' => 'This Value'],
],
'status' => 'Subscribed'
];
foreach ($object->dataFields as $dataRow) {
if ($dataRow->key === 'THIS_KEY') {
echo $dataRow->value;
break;
}
}
Output:
This Value
A functional search can look like this: (Demo)
$index = array_search('THIS_KEY', array_column($object->dataFields, 'key'));
if ($index !== false) {
echo $object->dataFields[$index]->value; // same output as above
}
If you want simpler access to multiple values in the subarray, then assign temporary keys: (Demo)
$assocDataFields = array_column($object->dataFields, null, 'key');
echo $assocDataFields['THIS_KEY']->value;
echo "\n";
echo $assocDataFields['FULLNAME']->value;
Output:
This Value
Tom Jones
I have an array tree from a database, I want to change the key of a child element in this case the second array 'eric'=>array into integer '0'=>array as follow :
0 => Array
('text' => 'paris',
'nodes' => Array
('eric' => Array
( 'text' => 'eric',
'nodes' => Array
(0 => Array
(
'text' => 'so.png',
),
),
),
),
),
there is my code :
while($d = mysqli_fetch_assoc($result)) {
if(!isset($data[$d['country']])) {
$data[$d['country']] = array(
'text' => $d['country'],
'nodes' => array()
);
}
if(!isset($data[$d['country']]['nodes'][$d['name']])) {
$data[$d['country']]['nodes'][$d['name']] = array(
'text' => $d['name'],
'nodes' => array()
);
}
array_push($data[$d['country']]['nodes'][$d['name']]['nodes'], $d['n_doc']);
}
To change all of the child keys to numeric values, you can simply just use array_values()
Live Demo
for($i = 0; $i <= count($data) -1; $i++) { # This loops through each country
$data[$i]['nodes'] = array_map(function($node) { # This preserves the parent text value
return array_values($node); # [0] => Paris, [1] => array(...)
}, $data[$i]['nodes']);
}
Output
[ ... => [ text => Paris, nodes => [ 0 => Paris, 1 => [ ... ] ] ... ] ... ]
can you change your code for this input:
Array
(
[0] => Array
(
[text] => paris
[nodes] => Array
(
[jacque] => Array
(
[text] => jacque
[nodes] => Array
(
[0] => 32.png
)
)
[anis] => Array
(
[text] => anis
[nodes] => Array
(
[0] => 5384a97ee9d6b (2).pd
)
)
)
)
[1] => Array
(
[text] => london
[nodes] => Array
(
[dodo] => Array
(
[text] => dodo
[nodes] => Array
(
[0] => 148782.svg
[1] => 333.png
)
)
[sd] => Array
(
[text] => sd
[nodes] => Array
(
[0] => 1014-favicon.ico
)
)
)
)
)
I have the following array
Array
(
[0] => Array
(
[text] => Array
(
[content] => I
[beginOffset] => 0
)
[partOfSpeech] => Array
(
[tag] => PRON
[aspect] => ASPECT_UNKNOWN
[case] => NOMINATIVE
[form] => FORM_UNKNOWN
[gender] => GENDER_UNKNOWN
[mood] => MOOD_UNKNOWN
[number] => SINGULAR
[person] => FIRST
[proper] => PROPER_UNKNOWN
[reciprocity] => RECIPROCITY_UNKNOWN
[tense] => TENSE_UNKNOWN
[voice] => VOICE_UNKNOWN
)
[dependencyEdge] => Array
(
[headTokenIndex] => 1
[label] => NSUBJ
)
[lemma] => I
)
...
I want to remove all elements that contain the string "_UNKNOWN" as they are not necessairy
how would I go about that?
Assuming all your 'UNKNOWN' are going to be in 'partOfSpeech', you can use this simple code to remove all the elements containing the string '_UNKNOWN':
$array = ['text' => ['content' => 'I', 'beginOffset' => 0], 'partOfSpeech' => ['tag' => 'PRON', 'aspect' => 'ASPECT_UNKNOWN', 'form' => 'FORM_UNKNOWN']]; // Example array
$array['partOfSpeech'] = array_filter($array['partOfSpeech'],
function($item) {
return strpos($item, '_UNKNOWN') === false;
});
print_r($array);
Output:
Array ( [text] => Array ( [content] => I [beginOffset] => 0 ) [partOfSpeech] => Array ( [tag] => PRON ) )
I'm trying to delete sub array of my multidimensional array, if any of the value is empty, than delete entire sub array. I want a universal function for the same! Dont want to type specific keys. And than ReIndex the newly formed array.
My array is like
Array
(
[0] => Array
(
[name] => Test
[mobile] => 613594551
[email] => test#test.com
)
[1] => Array
(
[name] => Test1
[mobile] => 613594552
[email] => test2#test.com
)
[2] => Array
(
[name] => Test2
[mobile] => 613594553
[email] => test3#test.com
)
[3] => Array
(
[name] => Test3
[mobile] => 613594554
[email] => test4#test.com
)
)
So if my array is
Array
(
[0] => Array
(
[name] =>
[mobile] => 613594551
[email] => test#test.com
)
[1] => Array
(
[name] => Test1
[mobile] =>
[email] => test2#test.com
)
[2] => Array
(
[name] => Test2
[mobile] => 613594553
[email] =>
)
[3] => Array
(
[name] => Test3
[mobile] => 613594554
[email] => test4#test.com
)
)
Than display
Array
(
[0] => Array
(
[name] => Test3
[mobile] => 613594554
[email] => test4#test.com
)
)
Elaborating on Martin's answer, you can use array_filter() for both the source array and the nested array:
$filtered_array = array_filter($array, function($item){
return count($item) == count(array_filter($item));
});
sort($filtered_array); // to reindex
Working example: https://eval.in/521449
Use array_filter() to iterate all records for each person and remove those that have an empty value. Number of records before and after array_filter() has to be equal if all records are filled. If they're not remove the person using unset().
Note, that this function works in-place, so it modifies the original array.
<?php
$array = [
[
'name' => 'Test1',
'mobile' => 123456789,
'email' => null
], [
'name' => 'Test2',
'mobile' => 123456789,
'email' => 'test2#test.com'
], [
'name' => null,
'mobile' => 123456789,
'email' => 'test3#test.com'
],
];
function removeEmpty(&$arr) {
foreach ($arr as $index => $person) {
if (count($person) != count(array_filter($person, function($value) { return !!$value; }))) {
unset($arr[$index]);
}
}
}
removeEmpty($array);
print_r($array);
Prints:
Array
(
[1] => Array
(
[name] => Test2
[mobile] => 123456789
[email] => test2#test.com
)
)
Assuming that an array item might have different keys:
$array = array(
0=>array('name'=>'','test'=>2),
1=>array('name'=>'sadad','test'=>2),
);
foreach($array as $index=>$item) {
$keys = array_keys($item); //here is the assumption
//you can define it before the foreach
//by checking the first array if YOU are 100% sure
//all items in the array have the same keys: name, mobile, email
foreach($keys as $key) {
if(empty($item[$key])) {
unset($array[$index]);
break;
}
}
}
var_dump($array);
Output:
array(1) {
[1]=>
array(2) {
["name"]=>
string(5) "sadad"
["test"]=>
int(2)
}
}
this is my php code.
while($fetchRes=mysql_fetch_assoc($query9)) {
$rows[] = array(
array('iso'=>$staff_id,
'name'=>$name,
'iso3'=>$last_name,
'numcode'=>$email
),);
}
echo '<pre>';
$rows=print_r($rows);
echo '</pre>';
after running this code i am getting the following output.
Array (
[0] => Array (
[0] => Array ( [id] => 008 [name] =>
dev [last_name] => abc [email] => abc#gmail.com ) )
[1] => Array ( [0] => Array ( [name] => 7002
[name] => Sheela [lastname] => Mbhhh [email] => 7002#iem.com ) )
but problem is that i want the following type of array
array(
array('id'=>'008 ',
'name'=>'dev ',
'last_name'=>'abc ',
'email'=>'abc#gmail.com',
),
array('id'=>'AL',
'name'=>'Albania',
'last'=>'ALB',
'email'=>'8',
)
means i dont want the extra things in my array like Array (
[0] =>, Array (
[1] =>
Then why do you use an array inside another array? ($rows[] = array(array(...)
Try this:
while($fetchRes=mysql_fetch_assoc($query9)) {
$rows[] = array(
'iso' => $staff_id,
'name' => $name,
'iso3' => $last_name,
'numcode' => $email
);
}