Try this:
function delete_row(&$array, $offset) {
return array_splice($array, $offset, 1);
}
function delete_col(&$array, $offset) {
return array_walk($array, function (&
offset) {
array_splice(
offset, 1);
});
}
Tested on Ideone: http://ideone.com/G5zRi0
Edit (Amade):
delete_col function can also be slightly modified to work with arrays with missing columns:
function delete_col(&$array, $key) {
return array_walk($array, function (&
key) {
unset(
key]);
});
}
This can be used e.g. when you need to iterate over an array and remove some columns in each step. A function using array_splice instead of unset would not be appropriate in such scenarios (it's offset-based and not key-based).
Answer from mpyw on Stack OverflowTry this:
function delete_row(&$array, $offset) {
return array_splice($array, $offset, 1);
}
function delete_col(&$array, $offset) {
return array_walk($array, function (&
offset) {
array_splice(
offset, 1);
});
}
Tested on Ideone: http://ideone.com/G5zRi0
Edit (Amade):
delete_col function can also be slightly modified to work with arrays with missing columns:
function delete_col(&$array, $key) {
return array_walk($array, function (&
key) {
unset(
key]);
});
}
This can be used e.g. when you need to iterate over an array and remove some columns in each step. A function using array_splice instead of unset would not be appropriate in such scenarios (it's offset-based and not key-based).
The PHP manual for array_walk() states (emphasis added):
Only the values of the array may potentially be changed; its structure cannot be altered, i.e., the programmer cannot add, unset or reorder elements. If the callback does not respect this requirement, the behavior of this function is undefined, and unpredictable.
That sounds to me as if mpyw's and Amade's answer might work but cannot be relied on.
A safer solution might be the following:
function delete_col(&$array, $key)
{
// Check that the column ($key) to be deleted exists in all rows before attempting delete
foreach ($array as &$row) { if (!array_key_exists(
row)) { return false; } }
foreach ($array as &$row) { unset(
key]); }
unset($row);
return true;
}
I have this array which is used to generate an excel file using PhpSpreadsheet. This is the array
$data =
array(
1 =>
array(
'A' => 'Project',
'B' => 'Execution.Key',
'C' => 'Execution.Assigned To',
'D' => 'Execution.Type',
'E' => 'Execution.Execution Date',
'F' => 'Execution.Actual',
'G' => 'Execution.Estimated',
'H' => 'Execution.Result',
'I' => 'Execution.Environment',
),
2 =>
array(
'A' => 'FOO',
'B' => 'FOO-KEY',
'C' => '',
'D' => 'MANUAL',
'E' => '2022-12-09',
'F' => NULL,
'G' => NULL,
'H' => 'Not Executed',
'I' => NULL,
)
);
I want to remove these columns from that array
$unwanted_cols = [
"Execution.Assigned To",
"Execution.Execution Date",
"Execution.Actual",
"Execution.Estimated",
"Execution.Result",
"Execution.Environment",
];
So in this example, we should only have these columns
$result = [ 'A' => 'Project', 'D' => 'Execution.Type' ]
So we remove the item using the key
function delete_cols($data, $unwanted_cols)
{
$cols_to_delete = [];
if (isset($data[1])) {
$headers = $data[1];
foreach ($headers as $key => $value) {
if (in_array($value, $unwanted_cols)) {
array_push($cols_to_delete, $key);
}
}
foreach ($data as $key => $value) {
if (!in_array($key, $cols_to_delete)) {
unset($data[$key]);
}
}
}
return $data;
}
}
it's not working though, why?
I don't want to remove by value, I want to remove by key, meaning if
'C' => 'Execution.Assigned To'
is in the $cols_to_delete array, then I want to loop the entire array and remove all values having the key 'C', which means I want to remove column C from the spreadsheet
How to delete a column of a multidimensional array in php? - Stack Overflow
php - How to remove multiple columns from the multi dimensional array? - Stack Overflow
php - Remove "columns" from the subarrays of a two dimensional array - Stack Overflow
php - removing array from multidimensional array - Stack Overflow
First when you do unset ($row[count($row)-2]); you are are just unsetting an index of the $row variable which is just a copy of the value from your array. So you are not deleting the value in the array.
Secondly, when you do $row[count($row)-2] you are assuming your $row has numerical indexes, which is not the case here. You want to delete the item_name index so you have to do something like unset($array[$index]['item_name']).
for(
length = count($array);
length; ++$i)
{
unset($array[$i]['item_name']);
}
An alternative to a foreach loop: array_walk() applies a user function to every item in an array:
array_walk( $arr, function(&$a){unset($a['item_name']);});
// ^^^ Use reference here to
// work on the original array
For example:
$arr = [
["item_id" => "1", "item_name" => "a"],
["item_id" => "2", "item_name" => "b"],
["item_id" => "3", "item_name" => "c"],
["item_id" => "4", "item_name" => "d", "value" => "10"],
["item_id" => "5", "item_name" => "e", "value" => "11"],
["item_id" => "6", "item_name" => "f", "value" => "12"]
];
array_walk( $arr, function(&$a){unset($a['item_name']);});
print_r($arr);
/* Output
Array
(
[0] => Array
( [item_id] => 1
)
[1] => Array
( [item_id] => 2
)
[2] => Array
(
[item_id] => 3
)
[3] => Array
( [item_id] => 4
[value] => 10
)
[4] => Array
( [item_id] => 5
[value] => 11
)
[5] => Array
( [item_id] => 6
[value] => 12
)
)
*/
You can try something like this:
$array = [
[
"picture_id" => "0",
"car_name" => "CA",
"from" => "2018",
"to" => "2020"
],
[
"picture_id" => "1",
"car_name" => "WA",
"from" => "2010",
"to" => "2019"
]
];
$whitelist = array("from", "to");
$finalArray = [];
foreach ($array as
record) {
foreach ($record as
item) {
if (!in_array(
whitelist)) {
$finalArray[
key] = $item;
}
}
}
print("<pre>".print_r($finalArray,true)."</pre>");
What will print out:
Array
(
[0] => Array
(
[picture_id] => 0
[car_name] => CA
)
[1] => Array
(
[picture_id] => 1
[car_name] => WA
)
)
A short explanation...Basically you are looping over multi dimensional array as
foreach($array as
value)
Where value is "inner" array, so in order to remove some elements from inner, and create a new multi dimensionalarray, you have to use keys, like in my example, from original array. So you than actually make an array like:
$newArray[
innerArray
And this gives you multi dimensional array. BR
Rather than having to go through each field to determine if it should be removed, you can use array_diff_key() to remove all of the columns in one go. This needs you to create a list of the fields you want to remove and for each record just get the difference between the record and the keys to remove...
// Keys to remove (note as key rather than value)
$remove = ["from" => 1, "to" => 1];
$finalArray = [];
foreach ($array as $record) {
$finalArray[] = array_diff_key($record, $remove);
}
print_r($finalArray);
foreach ($_SESSION["addedToCart"] as &$arr)
& turns your variable into a reference instead of a copy. Normally this would be sufficient. unset() only works on data within the current scope (so your foreach loop) leaving the original unchanged (See unset() for details).
Instead you can do:
foreach ($_SESSION["addedToCart"] as $key => $val)
{
if ($val["stoeltjes"] == $stoeltje && $val['film_id'] == $id) {
unset($_SESSION["addedToCart"][$key]);
}
}
Even if the suggested way with the reference should work normally, here's an example without it:
foreach ($_SESSION["addedToCart"] as $key => $arr) {
if ($arr["stoeltjes"] == $stoeltje && $arr['film_id'] == $id) {
unset($_SESSION["addedToCart"][$key]);
}
}
Have a look at the // comments
foreach ($array_leave_dates as $emp => $leave_type) {
// you treat $leave_type as array here
foreach ($leave_type as $leave_dates) {
// you treat $leave_type as string here
// doesn't feel right
if($leave_type == 'Maternity Leave') {
// you are unsetting with a value
//unset($array_leave_dates[ --> $leave_type <-- ]);
// i assume you want to delete the key
unset($array_leave_dates[$emp]);
}
else{
// $row doesn't seem to exist, looks wrong from here
echo $leave_dates[$row];
}
}
}
Not sure what your data source looks like:
<?php
// Remove the whole employee
$employees = array(
'emp1' => array('sick' => 'Mon - Tue'),
'emp2' => array('bun in oven' => '2016 - 2017'),
'emp3' => array('broken heart' => '2017 - ∞'),
);
foreach ($employees as $emp => $leave) {
foreach ($leave as $leaveName => $date) {
if($leaveName == 'bun in oven') {
unset($employees[$emp]);
}
}
}
print_r($employees);
// OR remove only 'Maternity' from the employee but keep everything else
<?php
$employees = array(
'emp1' => array('sick' => 'Mon - Tue', 'its friday and im not coming in' => 'Fri'),
'emp2' => array('bun in oven' => '2016 - 2017', 'sick' => 'Thu'),
'emp3' => array('broken heart' => '2017 - ∞'),
);
foreach ($employees as $emp => $leave) {
foreach ($leave as $leaveName => $date) {
if($leaveName == 'bun in oven') {
unset($employees[$emp][$leaveName]);
}
}
}
print_r($employees);
The following code will do what you want:
<?php
$a = 1;
$b = 2;
$c = 3;
$d = 4;
$arr = array(
array ( $b, $d, $c, $a, $b),
array ($c, $a),
array ( $b, $d, $c ),
array( $c, $d, $a, $b, $b)
);
echo "before:\n";
print_r($arr);
foreach($arr as $k1=>$q) {
foreach($q as $k2=>$r) {
if($r == $c) {
unset($arr[$k1][$k2]);
}
}
}
echo "after:\n";
print_r($arr);
?>
Output:
before:
Array
(
[0] => Array
(
[0] => 2
[1] => 4
[2] => 3
[3] => 1
[4] => 2
)
[1] => Array
(
[0] => 3
[1] => 1
)
[2] => Array
(
[0] => 2
[1] => 4
[2] => 3
)
[3] => Array
(
[0] => 3
[1] => 4
[2] => 1
[3] => 2
[4] => 2
)
)
after:
Array
(
[0] => Array
(
[0] => 2
[1] => 4
[3] => 1
[4] => 2
)
[1] => Array
(
[1] => 1
)
[2] => Array
(
[0] => 2
[1] => 4
)
[3] => Array
(
[1] => 4
[2] => 1
[3] => 2
[4] => 2
)
)
As you can see, all the 3's have gone...
Search the value in the sub array then unset it.
$search = 'c';
$result = array_map(function ($value) use ($search) {
if(($key = array_search($search, $value)) !== false) {
unset($value[$key]);
}
return $value;
}, $your_array);
Or you could use a loop too:
// this way change your original array
foreach ($your_array as &$sub_array) {
if(($key = array_search($search, $sub_array)) !== false) {
unset($sub_array[$key]);
}
}
var_dump($your_array);
array_filter is great for removing things you don't want from arrays.
$cart = array_filter($cart, function($x) { return $x['id'] != 15; });
If you want to use a variable to determine which id to remove rather than including it in the array_filter callback, you can use your variable in the function like this:
$value = 15;
$cart = array_filter($cart, function($x) use ($value) { return $x['id'] != $value; });
There are a lot of weird array functions in PHP, but many of these requests are solved with very simple foreach loops...
$value = 15;
foreach ($cart as $i => $v) {
if ($v['id'] == $value) {
unset($cart[$i]);
}
}
If $value is not in the array at all, nothing will happen. If $value is in the array, the entire index will be deleted (unset).
We can make this more simpler. Just get all column values using array_column.
Use array_filter with a custom callback to remove all empty string values.
If after filtering, size of array is 0, then that key needs to be unset from all
subarrays.
Note: The arrow syntax in the callback is introduced since PHP 7.4.
Snippet:
<?php
$data = array (
'HeaderRow' => Array (
'0' => 'Employee','1' => 'LaborHours', '2' => 0.1, '3' => 0.25, '4' => 0.5, '5' => 0.8
),
'r0' => Array (
'0' => 'Joe', '1' => 5, '2' => '','3' => '', '4' => 50, '5' => ''
),
'r1' => Array (
'0' => 'Fred', '1' => 5,'2' => 10, '3' => '', '4' => '', '5' => ''
)
);
$cleanup_keys = [];
foreach(array_keys($data['HeaderRow']) as $column_key){
$column_values = array_column($data, $column_key);
array_shift($column_values); // removing header row value
$column_values = array_filter($column_values,fn($val) => strlen($val) != 0);
if(count($column_values) == 0) $cleanup_keys[] = $column_key;
}
foreach($data as &$row){
foreach($cleanup_keys as $ck){
unset($row[ $ck ]);
}
}
print_r($data);
It figures, I work on this for a day and have a moment of clarity right after posting. The answer was that I wasn't leveraging the Keys.:
function array_cleanup($array)
{
$array = transpose($array);
foreach ($array as $key => $value)
{
$empty = true;
foreach ($value as $subkey => $subvalue)
{
if ($subkey != "HeaderRow") {
if (!empty($subvalue))
{
$empty = false;
}
}
}
if ($empty) {
unset($array[$key]);
}
}
$array = transpose($array);
return $array;
}