How to access the changing key in an associative multidimensional array - php

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

Related

How to remove multiple columns from the multi dimensional array? [duplicate]

This question already has answers here:
Remove unwanted elements from subarrays in multidimensional array
(3 answers)
Closed 6 months ago.
I have a multi dimensional array like below.
array:1 [
0 => array:3 [
"picture_id" => "0"
"car_name" => "CA"
"from" => "2020"
"to" => "2020"
]
]
I need to remove from & to from the above array and return result in same structure.
I have tried following code
$whitelist = array("from", "to");
$finalArray = [];
foreach ($records as $record) {
foreach ($record as $key => $item) {
if (!in_array($key, $whitelist)) {
$finalArray[$key] = $item;
}
}
}
But the result I am getting is not multi-dimensional array like this:
array:1 [
"picture_id" => "0"
"car_name" => "CA"
]
My expected result is:
array:1 [
0 => array:3 [
"picture_id" => "0"
"car_name" => "CA"
]
]
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 $k => $record) {
foreach ($record as $key => $item) {
if (!in_array($key, $whitelist)) {
$finalArray[$k][$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 $key => $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[$key] = $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);
Try This
$result = [];
foreach($yourArray as $key => $value){
unset($value['from']);
unset($value['to']); //You can unset as many columns as you want specifically.
$result[] = $value;
}
print_r($result);

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
...

php unable to update specific array value

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

php combine keys with values in associative multidimensional array

I'm trying to manipulate an associative multidimensional array. I've extracted the keys from an array that I want to apply to another's values . . .
These are the keys that I've extracted in another function
$keys = array (
"id" => "id",
"addr_street_num" => "addr_street_num",
"addr_street" => "addr_street",
"price" => "price",
"days" =>"days",
"state" => Array
(
"id" => "id",
"name" => "name"
),
"city" => Array
(
"id" => "id",
"web_id" => "web_id",
"name" => "name"
)
);
This array has the values I'd like to combine together
$vals = array (
"0" => "830680",
"1" => "20",
"2" => "Sullivan Avenue",
"3" => "333000",
"4" => "12",
"5" => Array
(
"0" => "4",
"1" => "Maryland",
),
"6" => Array
(
"0" => "782",
"1" => "baltimore",
"2" => "Baltimore",
)
);
When I try to do array_combine($keys, $val);
I get 2 Notices about Array to string conversion
I guess array_combine only works on one dimensional arrays, any ideas on how to approach this?
If $keys was modified could it be combined with the values - problem is the shape of $keys is what I want to end up with?
It can be done recursively.
function combine_recursive($keys, $values) {
$result = array();
$key = reset($keys);
$value = reset($values);
do {
if (is_array($value)) {
$result[key($keys)] = combine_recursive($key, $value);
} else {
$result[key($keys)] = $value;
}
$value = next($values);
} while ($key = next($keys));
return $result;
}
This works for me with your example arrays. I'm sure this will give you all kinds of weird results/errors if the array structures are different from each other at all.

Categories