I'm trying to delete an array where the key is [ITEM_ID] searching the value 4
I would need to remove the whole array, but I cannot do it.
Array
(
[0] => Array
(
[ITEM_ID] => 4
[ITEM_MODEL] => BASIC Armario
[ITEM_FABRICANTE] => 1
[ITEM_COLOR] => Wenge
[ITEM_QUANTITY] => 1
)
[1] => Array
(
[ITEM_ID] => 8
[ITEM_MODEL] => Armario 2 Puertas
[ITEM_FABRICANTE] => 1
[ITEM_COLOR] => Roble
[ITEM_QUANTITY] => 1
)
)
I'm trying with this code:
$array = array("ITEM_ID" => "4");
print_r($array);
unset($array['ITEM_ID']);
print_r($array);
You will have to loop through the array and unset the proper sub-array:
// begin looping
foreach($array as $key=>$value)
{
// check if ITEM_ID is 4
if($value['ITEM_ID'] == '4')
{
// unset the array item using the $key
unset($array[$key]);
// stop the loop
break;
}
}
Related
I have the following structure of an array which is decoded from a JSON object. From this array result I need to fork widgets for processing. It is an unstable JSON array so the parent keys may differs in future but the widgets will not.
(
[2] => Array
(
[MA] => Array
(
[0] => Array
(
[activities] => Array
(
[0] => Array
(
[activity_id] => 3
[activity_name] => Excavation
[activity_unique_id] => EXCAV-d435
[created_date] => 2021-02-08 21:42:53
[end_date] => 2021-02-08 21:42:08
[fk_client_id] => 1
[fk_main_activity] => 3
[fk_project_id] => 2
[relation_type] => MA-A-SA-W
[start_date] => 2021-02-08 21:42:08
[widgets] => Array
(
[0] => Array
(
[activity_mapping] => STRUC-be4c
[check_box_val] => 0
[checkbox_unique_id] => EXCAV-dceae
[checkbox_widget_id] => 5
[created_date] => 2021-02-08 21:43:12
)
)
)
)
[created_date] => 2021-02-08 21:42:44
[end_date] => 2021-02-08 21:42:08
[fk_client_id] => 1
[fk_floor_ids] => 7
[fk_project_id] => 2
[main_activity_id] => 3
[main_activity_name] => Structure MA1
[main_activity_unique_id] => STRUC-be4c
[relation_type] => MA-A-SA-W
[sequence_no] => 1
[start_date] => 2021-02-08 21:42:08
[tower_ids] => 4
[widgets_ids] =>
)
...
it is a big source So I cut shorted it. From the above result set I only need to fork the following widgets object.
[widgets] => Array
(
[0] => Array
(
[activity_mapping] => STRUC-be4c
[check_box_val] => 0
[checkbox_unique_id] => EXCAV-dceae
[checkbox_widget_id] => 5
[created_date] => 2021-02-08 21:43:12
)
)
)
Thanks in advance.
This recursive function searches for the first occurrence of a key in a multidimensional array and returns its value.
function array_find_key(array $array, $key) {
if (array_key_exists($key, $array)) {
return [$key => $array[$key]];
} else {
foreach($array as $item) {
if (is_array($item) && $result = array_find_key($item, $key)) {
return $result;
}
}
}
}
$result = array_find_key($array, 'widgets');
fiddle
The answer from #id'7238 is designed to search for a qualifying value in the current level before attempting to traverse a deeper level. The nuance in my answer (which does not call array_key_exists()) is that it checks keys as it traverses a level and will go down a level as soon as a non-qualifying subarray is encountered.
While looping, if the key is found, the payload is returned (and potentially passed up the recursive stack). If a value is array type data, then the next level down is processed -- if that level contains a qualifying key, it is passed up the stack.
If there are no qualifying keys in the input array, then null will be returned.
Code: (Demo)
function searchByKey(array $array, $find) {
foreach($array as $k => $v) {
if ($k === $find) {
return [$k => $v];
}
if (is_array($v)) {
$result = searchByKey($v, $find);
if ($result) {
return $result;
}
}
}
}
var_export(searchByKey($a, 'foo'));
For fun, if the nesting level will be the same just with the keys being different, this will give you the widgets array:
$result = current(current(current(current(current($array)))))['widgets'];
This will give you the array under the widgets array:
$result = current(current(current(current(current(current($array)))))['widgets']);
The first example will only work if the widgets array is 5 levels deep in the array and for the second if there is only 1 array under widgets (if there are more you will get the first).
I have an array coming from my database and simply it consists of questions and answers. I am trying to merge 2 arrays and create multidimensional array if values are more than one.
Array
(
[0] => Array
(
[question_id] => 1
[option_id] => 1
)
[1] => Array
(
[question_id] => 2
[option_id] => 3
)
[2] => Array
(
[question_id] => 3
[option_id] => 5
)
[3] => Array
(
[question_id] => 3
[option_id] => 6
)
)
I've tried to separate answers and questions to 2 different arrays but couldn't figure how to merge them again.
$user_questions = array_column($answers, 'question_id');
$user_answers = array_column($answers, 'option_id');
What I need is (question 3 has 2 answers) :
Array
(
[1] => 1
[2] => 3
[3] => Array (5, 6)
)
You can group your data like this as you fetch the results from your query instead of processing it after the fact. To get the array you have now, you're currently doing something like this:
while ($row = $stmt->someFetchMethod()) {
$result[] = $row;
}
Instead, use the question id as the key in your result array, and append the option id to an array at that key.
while ($row = $stmt->someFetchMethod()) {
$result[$row['question_id']][] = $row['option_id'];
}
Below code will create a new array by looping the existing array.
// Considering your existing array to be like this
$array = array(
'0' => array('question_id' => 1,'option_id' => 1),
'1' => array('question_id' => 2, 'option_id' => 3 ),
'2' => array('question_id' => 3,'option_id' => 5),
'3' => array('question_id' => 3,'option_id' => 6)
);
//define new array
$new_array = array();
// loop the array
foreach($array as $key=>$value){
// if the option/answer is already set to to question key
if(isset($new_array[$value['question_id']])){
// if question key is an array, push new option to that array
if(is_array($new_array[$value['question_id']])){
array_push($new_array[$value['question_id']], $value['option_id']);
}else{
// convert question key to array with the old value and new option value
$new_array[$value['question_id']] = array($new_array[$value['question_id']],$value['option_id']);
}
}
else{
// assing option as value to question key
$new_array[$value['question_id']] = $value['option_id'];
}
}
print_r($new_array);
Out put:
Array
(
[1] => 1
[2] => 3
[3] => Array
(
[0] => 5
[1] => 6
)
)
I'm trying to merge/sums 2 arrays that can contain integers or more arrays (themselves containing integer).
When the values are integers, I need to sum them in the final array.
When the values are arrays, I need to loop through the values and sum them in the final array.
If a value or a sub-array exists only in 1 of the base array, it needs to be added in the sub-array of the final array. (This is what I can't do)..)
My arrays are like this:
ARRAY 1
[1466859600] => Array
(
[TOTAL] => 27217
[AAA] => Array
(
[FD_CDP] => 1746
[LO_SC_MIC] => 4654
[FD_ATS] => 893
[CDP] => 40
[SUPERVISION] => 9
[CONTROL] => 4
[ATS] => 4
[EVT_ACK] => 3
)
[BBB] => Array
(
[FD_CDP] => 1376
[LO_SC_MIC] => 4606
[FD_ATS] => 826
[FD_ATSS] => 451
[LO_SFRC] => 4
[FD_S2] => 259
[2_LOSC] => 2
)
[CCC] => Array
(
[FD_CDP] => 1333
[LO_SC_MIC] => 4725
[FD_ATS] => 856
[CONTROL] => 4
[ATS] => 2
[EVT_ACK] => 5
)
ARRAY 2
[1466859600] => Array
(
[TOTAL] => 95406
[AAA] => Array
(
[FD_ATSS] => 1719
[LO_SC_MIC] => 16830
[CONTROL] => 16
[NEW] => 7
[NOEL] => 206
)
[BBB] => Array
(
[SUPERVISION] => 23
[CDP] => 158
[CONTROL] => 40
[2_LOSC] => 14
[ATS] => 6
[EVT_ACK] => 4
)
[CCC] => Array
(
[EVT_ACK] => 167
[LO_SFRC] => 248
[SUPERVISION] => 23
)
I wrote a function like this :
function sumArrayValues($array1, $array2)
{
foreach ($array1 as $key => $value)
{
if (is_array($array1[$key]))
{
echo "it's an array\n I need to reloop\n";
sumArrayValues($array1[$key], $array2[$key]);
}
else
{
echo "FIRST VALUE TO SUM\n";
print_r($array1[$key]."\n");
echo "SECOND VALUE TO SUM\n";
print_r($array2[$key]."\n");
$array1[$key] = (int)$array1[$key] +(int)$array2[$key];
echo "--------RESULT of SUM array1&2----------\n";
}
}
return $array1;
}
But this function doesn't take into account 2 (and probably more) cases: if the sub-array are not in the same order, if a sub-array or a value only exist in second array.
A example of function would be a good help, but on a more fundamental level, I even can't figure the algorithm to do that.
Any ideas ?
You can get all the keys for the foreach loop, live demo.
Note, you also can check if a key of any array is undefined, then save the defined value for the key.
function sumArrayValues($array1, $array2)
{
$keys = array_keys($array1 + $array2);
foreach ($keys as $key)
{
if (is_array($array1[$key]) || is_array($array2[$key]))
$array1[$key] = sumArrayValues($array1[$key], $array2[$key]);
else
#$array1[$key] = (int)$array1[$key] +(int)$array2[$key];
}
return $array1;
}
I have 2 arrays: Array1 and Array2. As you can see in Array1 I have 2 duplicate values. So what I want to do, is unset one of dublicates (doesn't matter which one) and as a result I need to unset value from Array2 with the same key as already unset value in Array1
Array1
(
[0] => 1331-14-2-45
[1] => 1344-1-4-22
**[2] => 1409-1-1-4**
[4] => 1312-14-1-23
**[5] => 1409-1-1-4**
[6] => 1365-10-3-30
)
AND
Array2
(
[0] => opticalSignalLevelTooLow1490nm#nemodel.GPON.4.6
[1] => opticalSignalLevelTooLow1490nm#nemodel.GPON.4.6
[2] => opticalSignalLevelTooLow1490nm#nemodel.GPON.4.6
[4] => deviceNotActive#nemodel.GPON.4.6
[5] => deviceNotActive#nemodel.GPON.4.6
[6] => opticalSignalLevelTooLow1490nm#nemodel.GPON.4.6
)
<?php
$array1 = array
(
0 => '1331-14-2-45',
1 => '1344-1-4-22',
2 => '1409-1-1-4',
4 => '1312-14-1-23',
5 => '1409-1-1-4',
6 => '1365-10-3-30',
);
$array1_tmp = $array1;
$array2 = array
(
0 => 'opticalSignalLevelTooLow1490nm#nemodel.GPON.4.6',
1 => 'opticalSignalLevelTooLow1490nm#nemodel.GPON.4.6',
2 => 'opticalSignalLevelTooLow1490nm#nemodel.GPON.4.6',
4 => 'deviceNotActive#nemodel.GPON.4.6',
5 => 'deviceNotActive#nemodel.GPON.4.6',
6 => 'opticalSignalLevelTooLow1490nm#nemodel.GPON.4.6',
);
$array1 = array_unique($array1);
$remove_keys = array_keys(array_diff_key($array1_tmp, $array1));
foreach($remove_keys as $k => $v) {
unset($array2[$v]);
}
You can use the array_unique() function, and maybe take a look at the Array functions list.
Use array_unique function and array_diff
$uniqueValues = array_unique($inputArray); //your first array
$deletedValues = array_diff($inputArray, $uniqueValues);
foreach($deletedValues as $key => $deletedValue){
unset($secondIput[$key]); //you second array
}
I have the following multidimensional array:
Array ( [0] => Array
( [id] => 1
[name] => Jonah
[points] => 27 )
[1] => Array
( [id] => 2
[name] => Mark
[points] => 34 )
)
I'm currently using a foreach loop to extract the values from the array:
foreach ($result as $key => $sub)
{
...
}
But I was wondering how do I see whether a value within the array already exists.
So for example if I wanted to add another set to the array, but the id is 1 (so the person is Jonah) and their score is 5, can I add the 5 to the already created array value in id 0 instead of creating a new array value?
So after the loop has finished the array will look like this:
Array ( [0] => Array
( [id] => 1
[name] => Jonah
[points] => 32 )
[1] => Array
( [id] => 2
[name] => Mark
[points] => 34 )
)
What about looping over your array, checking for each item if it's id is the one you're looking for ?
$found = false;
foreach ($your_array as $key => $data) {
if ($data['id'] == $the_id_youre_lloking_for) {
// The item has been found => add the new points to the existing ones
$data['points'] += $the_number_of_points;
$found = true;
break; // no need to loop anymore, as we have found the item => exit the loop
}
}
if ($found === false) {
// The id you were looking for has not been found,
// which means the corresponding item is not already present in your array
// => Add a new item to the array
}
you can first store the array with index equal to the id.
for example :
$arr =Array ( [0] => Array
( [id] => 1
[name] => Jonah
[points] => 27 )
[1] => Array
( [id] => 2
[name] => Mark
[points] => 34 )
);
$new = array();
foreach($arr as $value){
$new[$value['id']] = $value;
}
//So now you can check the array $new for if the key exists already
if(array_key_exists(1, $new)){
$new[1]['points'] = 32;
}
Even though the question is answered, I wanted to post my answer. Might come handy to future viewers. You can create new array from this array with filter then from there you can check if value exist on that array or not. You can follow below code. Sample
$arr = array(
0 =>array(
"id"=> 1,
"name"=> "Bangladesh",
"action"=> "27"
),
1 =>array(
"id"=> 2,
"name"=> "Entertainment",
"action"=> "34"
)
);
$new = array();
foreach($arr as $value){
$new[$value['id']] = $value;
}
if(array_key_exists(1, $new)){
echo $new[1]['id'];
}
else {
echo "aaa";
}
//print_r($new);