php unable to update specific array value - php

I am trying to compare two arrays and update specific array values based on conditions.
Getting attendance array of absent students:
$array1 =
array(
array("student_id" => "2",
"date" => "2016-04-24"),
array("student_id" => "6",
"date" => "2016-04-24"));
$attendance = json_decode(json_encode($array1));
Getting student list array of all students:
$array2 =
array(
array("student_id" => "1",
"Reason" => "",
"date" => "2016-04-24"),
array("student_id" => "2",
"Reason" => "",
"date" => "2016-04-24"),
array("student_id" => "3",
"Reason" => "",
"date" => "2016-04-24"),
array("student_id" => "6",
"Reason" => "1",
"date" => "2016-04-24"));
$students = json_decode(json_encode($array2));
Taking out only student IDs of absent students:
foreach($attendance as $att)
{ $atts[] = $att->student_id;}
Here I am trying to find out if any of the students ID in student array matches with ID in absent array. If ID is present then I will update the Reason as "1". Else will make the reason as 0
for ($i = 1; $i <= count($students); $i++) {
if(in_array($atts[$i],$students))
{
$students->Reason='1';
}
else
{
$students->Reason='0';
}
}
echo '<pre>',print_r($students,1),'</pre>';
Here I am unable to update student array with "reason" values.

If you just want to compare student_id from array1 with student_id from array2, and set Reason in array2 if they correspond to each other, use this :
foreach ($array1 as $key1 => $value1) {
foreach ($array2 as $key2 => $value2) {
if ($value1['student_id'] == $value2['student_id']) {
$array2[$key2]['Reason'] = 1;
} else if ($array2[$key2]['Reason'] != 1) {
$array2[$key2]['Reason'] = 0;
}
}
}

Related

Group and filter array rows based on multiple column values

I have an array of rows containing room availability for different dates for a hotel. I need to filter the array to identify on which dates the hotel has no vacancy.
$array = [
["room_id" => "1", "date" => "01-07-2022", "available" => "A"],
["room_id" => "2", "date" => "01-07-2022", "available" => "A"],
["room_id" => "1", "date" => "02-07-2022", "available" => "A"],
["room_id" => "2", "date" => "02-07-2022", "available" => "U"],
["room_id" => "1", "date" => "03-07-2022", "available" => "U"],
["room_id" => "2", "date" => "03-07-2022", "available" => "U"],
["room_id" => "1", "date" => "04-07-2022", "available" => "U"],
]
01-07-2022 has only A entries, so that date has vacancies.
02-07-2022 has A and U entries, so that date has vacancies.
03-07-2022 has only U entries, so that date has NO vacancies.
04-07-2022 has only U, so that date has NO vacancies.
The expected result indicating dates with no vacancies::
[
[
"room_id" => "2",
"date" => "03-07-2022"
"available" => "U"
],
[
"room_id" => "1",
"date" => "04-07-2022"
"available" => "U"
],
]
I've tried the following:
foreach ($roomsArr as $room) {
if ($room['availability'] === 'U') {
$unavailable[] = $room;
}
else if ($room['availability'] === 'A') {
$available[] = $room;
}
}
foreach ($unavailable as $uv) {
foreach ($available as $av) {
if ($av['date'] === $uv['date']) {
if ($av['availability'] === 'A' && $uv['availability'] === 'A') {
}
else if ($av['availability'] === 'A' && $uv['availability'] === 'U') {
}
else if ($av['availability'] === 'U' && $uv['availability'] === 'U') {
$arr1[] = $av;
}
}
}
}
I'll show two approaches/snippets with different benefits.
First divide them into vacant and non-vacant arrays, then group the data in those two arrays by date so that you don't have duplicate entries per date.
After the data is separated and grouped, you merely need to compare the dates/keys where there are no vacancies against dates where there are vacancies. What is left over will be the dates when the hotel has no vacancies.
This is potentially easier to conceptualize, but will not be as performant as the second snippet because it executes two separate iterating techniques.
Code: (Demo)
$hasVacancy = [];
$hasNoVacancy = [];
foreach ($array as $row) {
if ($row['available'] === 'A') {
$hasVacancy[$row['date']] = $row;
} else {
$hasNoVacancy[$row['date']] = $row;
}
}
var_export(
array_values(array_diff_key($hasNoVacancy, $hasVacancy))
);
Output:
array (
0 =>
array (
'room_id' => '2',
'date' => '03-07-2022',
'available' => 'U',
),
1 =>
array (
'room_id' => '1',
'date' => '04-07-2022',
'available' => 'U',
),
)
More efficiently, you'll need to maintain a lookup array to ensure that a date has NO available rooms. I recommend this snippet if you can understand the logic. It only needs to traverse the input array one time.
Code: (Demo)
$hasVacancy = [];
$result = [];
foreach ($array as $row) {
if ($row['available'] === 'A') {
$hasVacancy[$row['date']] = $row; // store available as reference
unset($result[$row['date']]); // remove potentially stored unavailable row for date
} elseif (!isset($hasVacancy[$row['date']])) {
$result[$row['date']] = $row; // is unavailable and no availables found
}
}
var_export(array_values($result));
// same result as previous snippet

Update array with post values

im currently trying to update an array with values from another one.
Basically there is a form where you can update data for an object, the form sends a json array like so:
{
"name": "Test2",
"address": "Adresas 2",
"object_id": "44",
"job_id": [
"31",
"33"
],
"amount": [
"500",
"500"
]
}
My goal is to update another array that is being fetched from the database with values of job_idd and amount.
The array from database looks like so:
{
"jobs": [
{
"id": "31",
"amount": "500",
"have": 250
},
{
"id": "33",
"amount": "500",
"have": 0
}
]
}
I need to update the second array values "amount" with the posted values from the first array "amount", but so that the second array still has the original "have" values
I tried using nested foreach method:
$object_id = $_POST['object_id'];
$data = json_encode($_POST);
$json = json_decode($data, true);
$i = 0;
foreach($json['job_id'] as $item) {
$job_id = $item;
$query33 = "SELECT * FROM `objektai` WHERE id='$object_id'";
$result33 = mysqli_query($conn, $query33) or die(mysqli_error($conn));
while($row2 = mysqli_fetch_array($result33)){
$job_info = $row2['info'];
}
$json_22 = json_decode($job_info, true);
foreach ($json_22['jobs'] as $key2 => $entry2) {
$have = $json_22['jobs'][$key2]['have'];
}
$result["jobs"][] = array(
'id' => $job_id,
'kiekis' => $json['amount'][$i],
'turima' => $have,
);
$i++;
}
Usinng the example above the foreach prints the values 2 times and my updated json "have"
has a value of 0, the "amount" entries are updated correctly
Thanks in advance for you help!
UPDATE
adding var_export($_POST):
array ( 'name' => 'Test2',
'address' => 'Adresas 2',
'object_id' => '44',
'job_idd' => array (
0 => '31',
1 => '33',
),
'darbo_kiekis' => array (
0 => '500',
1 => '500',
),
)
When you're looping through the array from the database, you need to compare the id value with $obj_id.
I've also shown below how to use a prepared statement to prevent SQL injection.
I've removed lots of unnecessary code:
No need to convert $_POST to/from JSON.
Use $i => in the foreach loop to get the array index.
You don't need a while loop when processing the query results if it only returns one row.
You don't need $key2, you can just use $entry2.
$object_id = $_POST['object_id'];
$query33 = "SELECT * FROM `objektai` WHERE id = ?";
$stmt33 = $conn->prepare($query33);
$stmt33->bind_param('i', $job_id);
foreach($_POST['job_id'] as $i => $job_id) {
$stmt33->execute();
$result33 = $stmt33->get_result();
$row2 = $result33->fetch_assoc();
$job_info = $row2['info'];
$json_22 = json_decode($job_info, true);
foreach ($json_22['jobs'] as $entry2) {
if ($entry2['id'] == $job_id) {
$result["jobs"][] = array(
'id' => $job_id,
'kiekis' => $json['amount'][$i],
'turima' => $entry2['have']
);
}
}
}

How to access the changing key in an associative multidimensional array

I have this array:
array: [
0 => array: [
"key 1" => "user 1",
"count" => "14"
],
1 => array: [
"key 2" => "user 2",
"count" => "7"
],
2 => array: [
"key 2" => "user 1",
"count" => "1"
]
]
I have to count the count values ​​for each key. But the names of keys have different names. And I do not know how to get access to them.
I want to get such result:
array: [
0 => array: [
"user" => "user 1",
"key 1" => "14",
"key 2" => "1",
],
1 => array: [
"user" => "user 2",
"key 2" => "7"
]
I tried to use two foreach loops
foreach ($result as $k=>$v)
{
foreach ($v as $k2=>$v2) {
$final[]["user"] = $result[$k][$k2];
}
}
But the result is incorrect
You could try something like this :
$result = [
["key 1" => "user 1", "count" => "14"],
["key 2" => "user 2", "count" => "7"],
["key 2" => "user 1", "count" => "1"]
];
$out = [] ; // output array
foreach ($result as $val) {
$keys = array_keys($val); // get the keys "key 1", "count" as array
$uid = reset($val); // get the first value "user 1"
$out[$uid]['user'] = reset($val); // store the user name
$out[$uid][reset($keys)] = $val['count']; // store the count into "key N" key.
}
$out = array_values($out); // reindex keys
print_r($out); // output data (optional)
Outputs :
Array
(
[0] => Array
(
[user] => user 1
[key 1] => 14
[key 2] => 1
)
[1] => Array
(
[user] => user 2
[key 2] => 7
)
)
I assumed user x and key x were just placeholders for any values.
$b = array();
foreach ($a as $row)
{
$values = array_values($row);
$keys = array_keys($row);
//Extract data from keys / values
$user = $values[0];
$key = $keys[0];
$count = $values[1];
//Create element in output array and insert user info
if ( ! isset($b[$user]))
{
$b[$user] = array('user' => $user);
}
//Add key info
$b[$user][$key] = $count;
}
//Rewrite array keys to 0, 1, 2, ...
$b = array_values($b);
edit: comments added

Map two dimensional php array to 1 dimension

I have array inside array:
{
"0" => array("key" => "code", "id" => "4", "value" => "yes"),
"1" => array("key" => "parameter", "id" => "4", "value" => "0"),
"2" => array("key" => "code", "id" => "5", "value" => "no"),
etc...
}
This is what I want to do: I want to have one dimension array in which key would be "id" and value would be "value". However, I need to filter out entries whose key is "parameters". So, in this example, the final array should look like this:
{
"4" => "yes",
"5" => "no"
}
I just can't seem to figure out how to do this. Could you please help me a bit? I tried writing this foreach inside foreach but I just can't wrap my head around how to filter data.
foreach ($settings AS $key => $value) {
$id = null;
$value = null;
foreach ($value AS $key2 => $value2) {
// No idea how to filter out uneccesary entries and save the correct ones
}
$finalArray[$id] = $value;
}
This should do it :
$finalArray = array();
foreach ($settings as $setting) {
if ($setting['key'] != 'parameter') {
$finalArray[$setting['id']] = $setting['value'];
}
}
Assuming all your entries have keys 'key', 'id' and 'value'.
use array_column and array_filter like this, if you want to filter more keys add them to out_keys array :
<?php
$array = [
["key" => "code", "id" => "4", "value" => "yes"],
["key" => "parameter", "id" => "4", "value" => "0"],
["key" => "code", "id" => "5", "value" => "no"]
];
$out_keys = ['parameter'];
$result = array_column(array_filter($array, function($item) use($out_keys) {
return !in_array($item['key'], $out_keys);
}), 'value', 'id');
echo "<pre>";
print_r($result);
output:
Array
(
[4] => yes
[5] => no
)
Assuming $data is your starting array, the code below will output what you want in $result
$result = [];
foreach(array_filter($data, function($el){return $el['key']!='parameter';}) as $el){
$result[$el['id']] = $el['value'];
}
Live demo

How to check if an array key value has an element

I have an array like this
Array
(
[0] =>
[
"18.06.2016",
"18.06.2016",
"18.06.2016",
"Test Test",
"Test Name",
"Michael Dean",
"London",
"1",
"980.00",
"",
"",
"875.00",
"875.00",
"0",
"64.81",
"0",
"810.19"
]
[1] =>
[
"18.06.2016",
"18.06.2016",
"18.06.2016",
"Tray 1",
"Test Name",
"Adam Richards",
"London",
"1",
"980.00",
"",
"",
"105.00",
"105.00",
"0",
"7.78",
"0",
"97.22"
]...
I want to check if the array key value has 1, after London or not?
Like in the first array key, the value goes like this order:
...,"Test Name","Michael Dean","London","1",...
How can I do that?
If the order is always the same you can just loop through.
foreach ($array as $key => $value) {
if ($value[4] == 'London' && $value[5] == 1) {
echo '$array['.$key.'] has London and 1 as key 4 and 5';
}
}
Though you have not appointed keys to the sub-arrays, they still have default keys and you can use these to get to the values you want.
Edit
Taking a look at your array I see that there is no logic to the order of the keys. You will not be able to find the values you are looking for unless you assign keys such as town, id, date, name to them.
For example:
array(
'0' => array(
'name' => 'John Doe',
'town' => 'London',
'active' => 1,
)
);
Use regular foreach loop to check if London value is followed by 1:
// $arr is your initial array
foreach ($arr as $k => $v) {
if ($v[6] == 'London') {
$hasValue = ($v[7] != 1)? "NOT" : "";
echo "Item with key $k has 'London' which is $hasValue followed by 1". PHP_EOL;
}
}
The exemplary output:
Item with key 0 has 'London' which is followed by 1
Item with key 1 has 'London' which is followed by 1
...

Categories