I am trying to unset the key which is equal to 'null' in my multidimensional array but the codes I've work with is not working so I tried to run it online. But even in online it does not work so I think there is something wrong in my codes.
My link for code is https://eval.in/591584
And this is my array:
$array = array(
'6' => array(
'null' =>array(
'null'=>array(
'11:04'=>array(
'id' => '22'
)
)
),
'1'=>array(
'2'=>array(
'11:04'=>array(
'id' => '22'
)
)
),
)
);
What I want is to remove the key with name null.
The output I want is below where the null key is unset:
$array = array(
'6' => array(
'1'=>array(
'2'=>array(
'11:04'=>array(
'id' => '22'
)
)
),
)
);
The code I've done so far is:
foreach($array as $devp => $dev){
foreach($dev as $comp => $com){
if($comp == null){
unset($array[$devp][$comp]);
}
}
}
But it's not working. I declared this condition ($comp == null) as comparing If $comp is equal to null. It should unset the array. What am I missing please help me.
In PHP null is a special datatype. And your key with value 'null' is a string.
So proper comparison is:
if ($comp == 'null') { // see quotes?
// do something
}
Related
Here is what phpunit says:
1) Asgard\Entity\Tests\EntityTest::testToArray
Failed asserting that two arrays are equal.
--- Expected
+++ Actual
## ##
Array (
'id' => null
'title' => 'Test Title'
'content' => 'Test Content'
'published' => 2015-03-04T11:19:50+0000
'comments' => Array (
0 => Array (
'id' => null
'content' => 'foo'
'published' => 2015-03-04T11:19:50+0000
'another_property' => null
'news' => null
)
1 => Array (
'id' => null
'content' => 'bar'
'published' => 2015-03-04T11:19:50+0000
'another_property' => null
'news' => null
)
2 => Array (
'id' => null
'content' => 'baz'
'published' => 2015-03-04T11:19:50+0000
'another_property' => null
'news' => null
)
)
'another_property' => null
)
https://travis-ci.org/asgardphp/asgard/jobs/53029084
There is no difference between "expected" and "actual". The tests usually pass, but sometimes would fail on this.
Found the issue. Elements were not in the same order. A bit annoying though that the output doesn't show it.
I have replaced assertEquals with:
$this->assertTrue($this->similar_arrays($arr1, $arr2));
protected function similar_arrays($a, $b) {
if(is_array($a) && is_array($b)) {
if(count(array_diff(array_keys($a), array_keys($b))) > 0)
return false;
foreach($a as $k => $v) {
if(!$this->similar_arrays($v, $b[$k]))
return false;
}
return true;
}
else
return $a === $b;
}
Since you're using DateTime in your tests - Are you sure you aren't getting test that start in one second, and finish in another so there is a second difference in the timestamps depending on which stage you look at them? - Using dynamic dates and time in tests is a pretty common reason for occasional failed tests.
Check if you have EOL in your values.
If you have a value like so:
'x' => 'line1
line2'
change it to
'x' => "line1\nline2"
Note: this may not answer direct issue the OP had, but this is what worked for me.
This question already has answers here:
PHP - Checking if array index exist or is null [duplicate]
(3 answers)
Closed 8 years ago.
I have this array I'm doing like so:
Turns out some of those var aren't always set which cause undefined index issues when trying to inserting it into the db?
Is there a quick way to check each value is set before adding it to the array?
$show_insert = array(
'title' => $show_data['title'],
'thetvdb_id' => $show_data['tvdbid'],
'release_date' => $show_data['FirstAired'],
'lastupdatethetvdb' => $show_data['lastupdatethetvdb'],
'moviedb_id' => $show_data['moviedb_id'],
'imdb_id' => $show_data['IMDB_ID'],
'img_id' => $show_data['tvdbid'],
'media_type' => 1,
'status' => $show_data['status'],
'length' => $show_data['runtime'],
'network' => $show_data['network'],
'overview' => $show_data['overview'],
'seasons' => $show_data['seasons'],
'episodes' => $show_data['episodes'],
'homepage' => $show_data['homepage'],
'last_airdate' => $show_data['last_air_date'],
'vote_average' => $show_data['vote_average']
);
You can use the ternary operator and isset(). We're checking if the variable and key are set (the part before ?). If it is set, use that variable (the part between ? and :) and if not, set to blank (the part after :).
Ternary operator works like:
$variable = ( comparison ? if true : if false );
Thus:
$show_insert = array(
'title' => ( isset( $show_data['title'] ) ? $show_data['title'] : '' ),
'thetvdb_id' => ( isset( $show_data['tvdbid'] ) ? $show_data['tvdbid'] : '' ),
[etc.]
);
if (isset($show_data['title']) {
$show_insert[title] = $show_data['title'];
}
This basically means that if $show_data[title] has been initialized then it will add it to the $show_insert array under the key 'title', if it has not been set, nothing will happen so there will be no array key 'title'
or for large arrays you could have:
public function check_set($array, $variable = null, $key_name)
if ($variable != null) {
$array[$key_name] = $variable;
}
check_set($show_insert, $show_data[title], $title = '"title"');
Expanding on the other answer:
I would use a function to simplify all that typing, also, I would use empty() instead of isset() but if you're just setting it to an empty string I suppose that part doesn't matter much.
function checkVal($val, $show_data){
return empty($show_data[$val]) ? "" : $show_data[$val];
}
$show_insert = array(
'title' => checkVal('title',$show_data),
'thetvdb_id' => checkVal('tvdbid',$show_data)
);
Quite a difficult to explain, but for example i have an array:
$lol = array(
'key' => 'value',
'key_1' => 'value 1',
'simple_value',
'0' => 'lol',
'key_array' => array(
'key_in_second' => 'value_with_key_in_second',
'value_in_second_array',
)
);
After json_encode it would be
{"key":"value","key_1":"value 1","0":"lol","key_array":{"key_in_second":"value_with_key_in_second","0":"value_in_second_array"}}
So is it possible somehow detect if in php array had the key or note? In my example elements 'simple_value', '0' => 'lol' have same key.
PHP doesn't care if the number 0 is in quotes or not. It is storing it as numeric 0, same as 'value_in_second_array' will be 0, as it was the first element without a key.
Basically,
array('0'=>'lol') is the same as array(0=>'lol') is the same is array('lol');
You'll see simple_value dissappeared, as it was overwritten with lol.
The JSON accurately reflects the php. For example, if you had this code:
<?php
$lol = array(
'key' => 'value',
'key_1' => 'value 1',
'simple_value',
'0' => 'lol',
'key_array' => array(
'key_in_second' => 'value_with_key_in_second',
'value_in_second_array',
)
);
print_r($lol);
The output would be:
Array
(
[key] => value
[key_1] => value 1
[0] => lol
[key_array] => Array
(
[key_in_second] => value_with_key_in_second
[0] => value_in_second_array
)
)
What happened here is that as simple_value didn't have a key, it was assigned a key of 0, but was then overwritten with lol which came next. You can also see how the value_in_second_array was automatically assigned a key of 0.
So, nothing to do with json_encode, you just never had the data in PHP.
I need help once again. I have an array and I need to extract earliest day weight value.
EDIT - EDIT - EDIT
array (
3 =>
array (
'id' => '20110211',
'Date' => '2011-02-11',
'Weight' => '195',
),
4 =>
array (
'id' => '20110213',
'Date' => '2011-02-13',
'Weight' => '160',
),
6 =>
array (
'id' => '20110310',
'Date' => '2011-03-10',
'Weight' => '200',
),
12 =>
array (
'id' => '20110301',
'Date' => '2011-03-01',
'Weight' => '55',
),
21 =>
array (
'id' => '20110215',
'Date' => '2011-02-15',
'Weight' => '120',
),
25 =>
array (
'id' => '20110322',
'Date' => '2011-03-22',
'Weight' => '250',
),
)
I've edited this and this code works:
function sortByDate ($arr1, $arr2)
{
return strcmp($arr1['Date'], $arr2['Date']);
}
// $arr is your array
usort($weight_tracker, 'sortByDate');
$earliest = $weight_tracker[0]['Weight'];
echo $earliest;
But since I have a form on this page which updates the array when array is updated - I got message Fatal error: Cannot use string offset as an array in
EDIT -> I've re-declared this as string, hence the ERROR ! be careful when using global and includes as everything can become a mess ! PHP is forgiving, but that "forgiveness" can cost a lot of time later on... :)
Thanks,
Peter
You could sort the array with a custom callback using usort() and then take the first element.
// $arr is your array
usort($arr, 'sortByDate');
$earliest = $arr[0];
function sortByDate ($arr1, $arr2)
{
return strcmp($arr1['Date'], $arr2['Date']);
}
This is one way of doing it:
function filter_min($a, $b) {
return ($a['Date'] < $b['date']) ? $a : $b;
}
$result = array_reduce($array, 'filter_min');
echo $result['Weight'];
Another way is to simply iterate over the array and find the smallest date.
$smallest = null; // array index of entry with smallest weight.
foreach ($array as $idx => $data) {
if (($data['Weight'] < $array[$smallest]['Weight']) || (is_null($smallest))) {
$smallest = $idx; // found a small weight, so save the index
}
}
echo $array[$smallest]['Date'];
I noticed that the dates are in reverse order with the latest date being pulled in first, and the earliest date last. Will it always be like that? If so, you can do this:
$index = count($array) - 1;
$earliestdate = $array[$index]['Date'];
You could also use array_reverse() to invert the array and make the first element the formerly last element.
If this is being pulled in from MySQL you could also alter the query to ORDER BY 'Date' DESC (or is it ASC that would get you what you want, can't remember)
I would like to retrieve the first key from this multi-dimensional array.
Array
(
[User] => Array
(
[id] => 2
[firstname] => first
[lastname] => last
[phone] => 123-1456
[email] =>
[website] =>
[group_id] => 1
[company_id] => 1
)
)
This array is stored in $this->data.
Right now I am using key($this->data) which retrieves 'User' as it should but this doesn't feel like the correct way to reach the result.
Are there any other ways to retrieve this result?
Thanks
There are other ways of doing it but nothing as quick and as short as using key(). Every other usage is for getting all keys. For example, all of these will return the first key in an array:
$keys=array_keys($this->data);
echo $keys[0]; //prints first key
foreach ($this->data as $key => $value)
{
echo $key;
break;
}
As you can see both are sloppy.
If you want a oneliner, but you want to protect yourself from accidentally getting the wrong key if the iterator is not on the first element, try this:
reset($this->data);
reset():
reset() rewinds array 's internal
pointer to the first element and
returns the value of the first array
element.
But what you're doing looks fine to me. There is a function that does exactly what you want in one line; what else could you want?
Use this (PHP 5.5+):
echo reset(array_column($this->data, 'id'));
I had a similar problem to solve and was pleased to find this post. However, the solutions provided only works for 2 levels and do not work for a multi-dimensional array with any number of levels. I needed a solution that could work for an array with any dimension and could find the first keys of each level.
After a bit of work I found a solution that may be useful to someone else and therefore I included my solution as part of this post.
Here is a sample start array:
$myArray = array(
'referrer' => array(
'week' => array(
'201901' => array(
'Internal' => array(
'page' => array(
'number' => 201,
'visits' => 5
)
),
'External' => array(
'page' => array(
'number' => 121,
'visits' => 1
)
),
),
'201902' => array(
'Social' => array(
'page' => array(
'number' => 921,
'visits' => 100
)
),
'External' => array(
'page' => array(
'number' => 88,
'visits' => 4
)
),
)
)
)
);
As this function needs to display all the fist keys whatever the dimension of the array, this suggested a recursive function and my function looks like this:
function getFirstKeys($arr){
$keys = '';
reset($arr);
$key = key($arr);
$arr1 = $arr[$key];
if (is_array($arr1)){
$keys .= $key . '|'. getFirstKeys($arr1);
} else {
$keys = $key;
}
return $keys;
}
When the function is called using the code:
$xx = getFirstKeys($myArray);
echo '<h4>Get First Keys</h4>';
echo '<li>The keys are: '.$xx.'</li>';
the output is:
Get First Keys
The keys are: referrer|week|201901|Internal|page|number
I hope this saves someone a bit of time should they encounter a similar problem.