Checking if array value exists in a PHP multidimensional array - php

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);

Related

Delete array from nested array

How can I delete the first Name arrray
[0] => Array
(
[Name] => John
)
from this one just if exist at lest two Name objects?
Array
(
[0] => Array
(
[Name] => John
)
[1] => Array
(
[Name] => James
)
[2] => Array
(
[Surname] => Doe
)
)
I'm trying to go through array with foreach, count how many arrays has name object and if there is more than one, then unset the first, but I'm not able to do that:
foreach($endArray as $arr)
{
if(count($arr['Name'])>1)
{
unset($endArray[0]);
}
}
In your code you use if(count($arr['Name'])>1) but I think that will never be true as the count will return 1 when the value is neither an array nor an object with implemented Countable interface.
To unset the first when there are more than one, you could count the number of occurrences of "Name" in the items using array_column.
If you want to remove the first array which has a key "Name" you could loop over the items and use unset using the $key.
Then break the loop to only remove the first encounter item.
$endArray = [
["Name" => "John"],
["Name" => "James"],
["Name" => "Doe"]
];
if (count(array_column($endArray, 'Name')) > 1) {
foreach ($endArray as $key => $arr) {
if (array_key_exists('Name', $arr)) {
unset($endArray[$key]);
break;
}
}
}
print_r($endArray);
Php demo
Output
Array
(
[1] => Array
(
[Name] => James
)
[2] => Array
(
[Name] => Doe
)
)
Another option is to keep track of the number of times the "Name" has been encountered:
$count = 0;
foreach ($endArray as $key => $arr) {
if (array_key_exists('Name', $arr) && $count === 0) {
$count++;
} else {
unset($endArray[$key]);
break;
}
}
Php demo

Pushing a sub array into the same array

I am trying to put content of one array into the same array. Here I have an array $mclass with values such as
Array
(
[0] => stdClass Object
(
[room_id] => 1,3,5
[day] => 1
[class_teacher] => TEA-2014-2
[final_exam_date] => 2015-09-21
)
)
You can see I have room_id index with 1,3,5 value. Now, I want to explode the room_id and get duplicate of same array index data with change of room_id and push into the array. and finally delete the current array index such as [0]. Here I want the final result as.
Array
(
[0] => stdClass Object
(
[room_id] => 1
[day] => 1
[class_teacher] => TEA-2014-2
[final_exam_date] => 2015-09-21
)
[1] => stdClass Object
(
[room_id] => 3
[day] => 1
[class_teacher] => TEA-2014-2
[final_exam_date] => 2015-09-21
)
[2] => stdClass Object
(
[room_id] => 5
[day] => 1
[class_teacher] => TEA-2014-2
[final_exam_date] => 2015-09-21
)
)
Here is my code for the same:
if(count($mclass)>0)
{
foreach($mclass as $mclasskey=>$mclass_row)
{
/* Room ID Calculation */
if(isset($mclass[$mclasskey]))
{
$temp_room_id = explode(',',$mclass_row->room_id);
if(count($temp_room_id)>1)
{
foreach($temp_room_id as $trkey=>$tr)
{
if(!in_array($temp_room_id[$trkey], $morning_class_semester))
{
array_push($morning_class_semester,$temp_room_id[$trkey]);
}
}
if(count($morning_class_semester)>0)
{
foreach($morning_class_semester as $mcskey=>$mcs)
{
$index_count = count($new_test);
$test[$index_count] = $mclass[$mclasskey];
$test[$index_count]->room_id = $morning_class_semester[$mcskey];
array_push($new_test,$test[$index_count]);
}
unset($mclass[$mclasskey]);
}
}
}
}
}
The code below does what you're looking for using only arrays. So you'll have to change the array access operators to -> since you're accessing an object. I'd do so, but it would break the example, so I'll leave that up to you.
Code Explained:
Loop through array selecting each subarray (object in your case), explode on the $item('room_id') ... ($item->room_id in your case) ... and create sub arrays, via loop, from that using the data from the original using each key. Remove the original item (which has the combined room_ids) and combine the placeholder and original array.
<?php
//Establish some data to work with
$array = array(
array(
"room_id" => "1,3,5",
"day" => 1,
"class_teacher" => "TEA-2014-2",
"final_exam_date" => "2015-09-21",
));
foreach ($array as $key => $item) {
$placeholder = array();
$ids = explode(',',$item['room_id']);
if (count($ids) > 1) {
foreach ($ids as $id) {
$push = array(
'room_id' => $id,
'day' => $item['day'],
'class_teacher' => $item['class_teacher'],
'final_exam_date' => $item['final_exam_date']
);
array_push($placeholder, $push);
}
$array = array_merge($array, $placeholder);
unset($array[$key]);
}
}
var_dump($array);
?>

error deleting sub-array based on key-value pair

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;
}
}

PHP Replacing Array Value

Im creating an array of products, each with an ID and score:
$savedProducts = array( 'product' => array("product_id" => $product_id,"product_score" => $score));
I want to be able to update the score by using the product_id as identifier.
I've tried:
foreach($savedProducts as $key => $val)
{
if ($val == $property_id )
{
$savedProducts[$key] = $score;
break;
}
}
Which keeps adding a new array item, rather than updating the original.
I think the issue is that my initial array setup then doesn't match the edited one.
Initial array:
Array
(
[product] => Array
(
[product_id] => 125026
[product_score] => 5
)
)
After trying to update score:
Array
(
[0] => Array
(
[product] => Array
(
[product_id] => 125026
[product_score] => 4
)
)
[1] => Array
(
[0] => Array
(
[product] => Array
(
[product_id] => 125026
[product_score] => 4
)
)
)
)
So it keeps addding elements, rather than updating the existing.
with PHP 5.5 use:
$savedProducts = array_column($savedProducts, NULL, 'product_id');
then you can access your product with:
$savedProducts[$product_id]
Please try this
foreach($savedProducts as $key => $val)
{
if($val['product_id'] == $property_id)
{
$savedProperties[$key]['product_score'] = $score;
break;
}
}

php - recreate array?

I've "inherited" some data, which I'm trying to clean up. The array is from a database which, apparently, had no keys.
The array itself, is pretty long, so I'm simplifying things for this post...
[0] => Array
(
[id] => 2
[uid] => 130
[eid] => 8
[ename] => Standard
[eaction] => Check
)
[1] => Array
(
[id] => 2
[uid] => 110
[eid] => 8
[ename] => Standard
[eaction] => Check
)
[2] => Array
(
[id] => 2
[uid] => 200
[eid] => 8
[ename] => Standard
[eaction] => Check
)
I'm trying to shift things around so the array is multidimensional and is grouped by ename:
[0] => Array
(
[Standard] => Array
(
[id] => 2
[uid] => 130
[eid] => 8
[eaction] => Check
)
)
[0] => Array
(
[Standard] => Array
(
[id] => 2
[uid] => 130
[eid] => 8
[eaction] => Check
)
)
[0] => Array
(
[Standard] => Array
(
[id] => 2
[uid] => 130
[eid] => 8
[eaction] => Check
)
)
Anyone know how to do something like this?
You can use usort() to sort an array by a user-defined function. That function could compare the ename fields. Then it's just a simple transformation. Like:
usort($array, 'cmp_ename');
function cmp_ename($a, $b) {
return strcmp($a['ename'], $b['ename']);
}
and then:
$output = array();
foreach ($array as $v) {
$ename = $v['ename'];
unset($v['ename']);
$output[] = array($ename => $v);
}
$outputarray = array();
foreach($inputarray as $value) {
$outputarray[] = array($value['ename'] => $value);
}
would accomplish what your examples seem to indicate (aside from the fact that your 'result' example has multiple things all with key 0... which isn't valid. I'm assuming you meant to number them 0,1,2 et cetera). However, I have to wonder what benefit you're getting from this, since all it appears to be doing is adding another dimension that serves no purpose. Perhaps you could clarify your example if there are other things to take into account?
$outputarray = array();
foreach($inputarray as &$value) {
$outputarray[][$value['ename']] = $value;
unset($value['ename']);
} unset($value);
I'm guessing that this is what you're asking for:
function array_group_by($input, $field) {
$out = array();
foreach ($input as $row) {
if (!isset($out[$row[$field]])) {
$out[$row[$field]] = array();
}
$out[$row[$field]][] = $row;
}
return $out;
}
And usage:
var_dump(array_group_by($input, 'ename'));
philfreo was right but he was also off a little. with his code every time you encounter an array element with an ['ename'] the same as one you've already gone through it will overwrite the data from the previous element with the same ['ename']
you might want to do something like this:
$output = array();
foreach ($YOURARRAY as $value) {
$output[$value['ename']][] = $value;
}
var_dump($output); // to check out what you get

Categories