I query a series of tables in order to print these, and I want to print all keys of each table even if the values are empty, but a specific set of keys which are the same for each table shall not be printed.
My query and fetch of the result in an array for one table:
$stmt = $db_conn->prepare("SELECT * FROM table;");
$stmt->execute();
$array = $stmt->fetchAll(PDO::FETCH_ASSOC);
$stmt->closeCursor();
var_export($array);returns:
array ( 0 => array ( 'a' => '1', 'b' => '2018-12-21', 'c' => '', 'd' => '', ), )
I prepared a list of bad keys in an array:
var_export($bad_keys);returns:
array ( 0 => array ( 'a' => '1', 'b' => '2019-01-05', ), )
For each table I want to exclude the bad keys {a, b} from the query result in $array by use of array_diff_key():
$array_new = array_diff_key($array, $bad_keys);
var_dump($array_new); returns empty:
array(0) { }.
$array_new should have the keys {'c', 'd'} but it has not. I don't see a mistake in my code. Please help.
array_diff_key is used to compute the difference between the keys of two or more arrays, i.e. a new array with all key/value pairs of the first array argument having keys not existing in any other array argument's keys are returned.
In your code, you try to compare the keys of your first array with an array of values (i.e. your $bad_keys, actually having numbered indexes), not the keys of the $bad_keys array. This is not how array_diff_key works.
Be sure to check out the reference at: http://php.net/manual/en/function.array-diff-key.php
One method giving you only the keys you are looking for as an array:
Just create a new array of the keys of the first array as values and then use array_diff to compare it with your $bad_keys.
To get the key/value pairs you can use this one (as Quasimodo's Clone suggested):
array_diff_key($array, array_flip($bad_keys))
UPDATE: The keys in the first array are also not at the same level as the keys in the $bad_array.
My mistake: In array_diff_key() I compared two multidimensional arrays without writing the index [0] for each array to be compared.
Solution: I added the index [0] to each array to be compared, and additionally I created an array from the result of array_diff_key()
$array = array( 0 =>
array(
'a' => '',
'b' => '',
'c' => '',
'd' => '',
),
);
$bad_keys = array( 0 =>
array(
'a' => '',
'b' => '',
),
);
$array_new = array( array_diff_key( $array[0], $bad_keys[0] ));
var_export( $array_new );
now returns the desired result:
array( 0 =>
array(
'c' => '',
'd' => '',
),
);
Related
I'm trying to find when the array has 2nd dimension values that are the same so I can deal with them.
I've looked at array_unique and other people who are asking a similar question, but they all delete the values instead of returning them.
Say I have an array like this:
array(
[0] => array(
[laps] => 7,
[corrected_time] => 18
),
[1] => array(
[laps] => 6,
[corrected_time] => 18
),
[2] => array(
[laps] => 7,
[corrected_time] => 18.5
)
)
I'd like to have it return: array(0,1) because they both have the same value for corrected time
Here is one approach. First get the values for corrected_time and convert them to strings (because we'll use them in array_count_values, which only works on ints and strings).
$times = array_map('strval', array_column($your_array, 'corrected_time'));
Then find all the values that occur more than once using array_count_values and array_filter.
$repeats = array_filter(array_count_values($times), function($time) {
return $time > 1;
});
After you have this list of repeated times, you can use it to filter your original array to only include items with repeated times.
$multiples = array_filter($your_array, function($item) use ($repeats){
return isset($repeats[(string) $item['corrected_time']]);
});
You can iterate over this, or if you only want the keys, you can get them with
$keys = array_keys($multiples);
In PHP Array index addition - different levels
is there a way to get array key names 'weighted', 'unweighted' , 'weighted_sum', 'unweighted_sum' rather than array index numbers?
So in the required output rather than [0] => Array, [1] => Array, [2] => ,
[3] =>
is there a way to get 'weighted' => Array, 'unweighted' => Array, 'weighted_sum' => , 'unweighted_sum' =>
tia
Jas
$keys = array_keys($m_aggregate);
$tot_aggregate = sum($m_aggregate, $f_aggregate);
$tot_aggregate = array_combine($keys, $tot_aggregate);
$array=array(
'weighted' => 'x',
'unweighted' => 'y',
'weighted_sum' => 'z'
);
echo $array['weighted'];
Multidimensional arrays
http://webcheatsheet.com/PHP/multidimensional_arrays.php
$colors = array(
'r' => 'a',
'g' => 'b',
'b' => 'c'
);
list($v, $k) = each($colors);
echo $v . " " . $k
Now the above prints r a
which I'm surprise since I thought the 'list' construct only works for numerical array. Why does it work?
Yes you are right list() only works on numerical arrays and assumes the numerical indices start at 0. but he reason why your code is working its because of each.
each traverse an array therefore converted the keys to numerical example if you run the following :
$foo = array("r"=>"a");
$bar = each($foo);
echo "<pre>";
print_r($bar);
Output
Array
(
[1] => a
[value] => a
[0] => r
[key] => r
)
You can use that array('r' => 'a'); has been converted to array(0 => 'r', 1 => 'a'); therefore you can now use list since they now have numerical keys
FROM PHP DOC
each Return the current key and value pair from an array and advance the array cursor.
each Returns the current key and value pair from the array array. This pair is returned in a four-element array, with the keys 0, 1, key, and value. Elements 0 and key contain the key name of the array element, and 1 and value contain the data.
Also
each() is typically used in conjunction with list() to traverse an array, here's an example:
Read the manual closer for each():
Returns the current key and value pair from the array array. This pair is returned in a four-element array, with the keys 0, 1, key, and value. Elements 0 and key contain the key name of the array element, and 1 and value contain the data.
So when you do each($colors), the following is returned:
array(0 => 'r' => 1 => 'a', 'key' => 'r', 'value' => 'a')
Then list() takes the values for 0 and 1 and assigns them to $v and $k respectively. Make sense?
I am trying to edit a plugin that is fetching a multidimensional array, then breaking it out into a foreach statement and doing stuff with the resulting data.
What I am trying to do is edit the array before it gets to the foreach statement. I want to look and see if there is a key/value combination that exists, and if it does remove that entire subarray, then reform the array and pass it to a new variable.
The current variable
$arrayslides
returns several subarrays that look like something like this (I remove unimportant variables for the sake of briefness):
Array (
[0] => Array (
[slide_active] => 1
)
[1] => Array (
[slide_active] => 0
)
)
What I want to do is look and see if one of these subarrays contains the key slide_active with a value of 0. If it contains a value of zero, I want to dump the whole subarray altogether, then reform the multidimensional array back into the variable
$arrayslides
I have tried a few array functions but have not had any luck. Any suggestions?
$arrayslides = array(0 => array ( 'slide_active' => 1, 'other_data' => "Mark" ),
1 => array ( 'slide_active' => 0, 'other_data' => "ABCDE" ),
2 => array ( 'slide_active' => 1, 'other_data' => "Baker" ),
3 => array ( 'slide_active' => 0, 'other_data' => "FGHIJ" ),
);
$matches = array_filter($arrayslides, function($item) { return $item['slide_active'] == 1; } );
var_dump($matches);
PHP >= 5.3.0
I know its not so efficient but still
foreach ($arraySlides as $key => $value)
{
if(in_array('0', array_values($value))
unset($arraySlides[$key]);
}
I have an empty array. I am able to push values using
array_push($list, item[0]);
But how do I push both key and value.
array_push($list[$key], $item[0])
this does not work.
$list['key']=$item[0];
should work.
Note: If you use array_push() to add one element to the array it's better to use $array[] = because in that way there is no overhead of calling a function.
If you want to maintain the key => value pairs you could use array_merge function.
$arr1 = array('apple' => 'fruit', 'banana' => 'fruit');
$arr2 = array('turnip' => 'vegetable', 'mushroom' => 'other');
$newArray = array_merge($arr1,$arr2)
This will return:
Array
(
[apple] => fruit
[banana] => fruit
[turnip] => vegetable
[mushroom] => other
)
But if two keys are the same in two arrays the one in the first array will be overwritten by the value in the second.