I got an array as follows.
I need to convert the values as integer
array:17 [
0 => array:2 [
"c" => "gmail"
"co" => "12"
]
1 => array:2 [
"c" => "dddd"
"co" => "2"
]
2 => array:2 [
"c" => "mmmmm"
"co" => "2"
]
3 => array:2 [
"c" => "dsf"
"co" => "2"
]
4 => array:2 [
"c" => "aaaa"
"co" => "1"
]
5 => array:2 [
"c" => "bbbb"
"co" => "1"
]
6 => array:2 [
"c" => "ccc"
"co" => "1"
]
7 => array:2 [
"c" => "yopmail"
"co" => "1"
]
8 => array:2 [
"c" => "yahoo"
"co" => "1"
]
]
I need to convert all values of the key co to integer ,where currently they are string.
Is this is the way to use the foreach,which didn't give me correct output
foreach($getDashboardDetails as $getDashboardDetails)
{
$getDashboardDetails['co']=(int)$getDashboardDetails['co'];
}
Hope Someone can help
I think the for loop is more what are you looking for as you want to change the initial array.
for($i=0;$i<=count($getDashboardDetails)-1;$i++) {
$getDashboardDetails[$i]["co"] = (int)$getDashboardDetails[$i]["co"];
$i++;
}
Or you can use foreach with a key-value pair on both dimensions, but I don't find it neccessary.
This might help you on your way(assuming $getDashboardDetails is the source array):
foreach($getDashboardDetails as $key => $value) {
foreach($value as $key1 => $value1) {
if ($key1 === "co") {
$getDashboardDetails[$key][$key1] = (int)$getDashboardDetails[$key][$key1];
}
}
}
Use below code to get it, your foreach is in incorrect foam.
$new_array = array();
foreach($getDashboardDetails as $key=>$value)
{
$new_array[$key]=array("c"=>$value['c'], "co"=>(int)$value['co']);
}
Now you have $new_array with expected results.
Related
category:
array:3 [▼
"78f895684c" => "blue"
"f71db561ba" => "green"
"3e231651de" => "blue"
]
numbersGroup:
array:3 [▼
0 => array:4 [▼
"uuid" => "78f895684c"
"price" => "10"
"discount" => "0"
"total" => "10.00"
]
1 => array:4 [▼
"uuid" => "f71db561ba"
"price" => "2"
"discount" => "0"
"total" => "2.00"
]
2 => array:4 [▼
"uuid" => "3e231651de"
"price" => "50"
"discount" => "10"
"total" => "40.00"
]
]
I try to create an array that sorts my items into categories, but also sums all items in a category together. This is what I have:
foreach ($numbersGroup as $group) {
$cat = $category[$group['uuid']];
unset($group['uuid']);
$numbersArray[$cat][] = $group;
}
With the result:
array:2 [▼
"blue" => array:2 [▼
0 => array:3 [▼
"price" => "10"
"discount" => "0"
"total" => "10.00"
]
1 => array:3 [▼
"price" => "50"
"discount" => "10"
"total" => "40.00"
]
]
"green" => array:1 [▼
0 => array:3 [▼
"price" => "2"
"discount" => "0"
"total" => "2.00"
]
]
]
This is what I am trying to achieve:
array:2 [▼
"blue" => array:2 [▼
0 => array:3 [▼
"price" => "60"
"discount" => "10"
"total" => "50.00"
]
]
"green" => array:1 [▼
0 => array:3 [▼
"price" => "2"
"discount" => "0"
"total" => "2.00"
]
]
]
This is my approach:
foreach ($numbersGroup as $group) {
$cat = $category[$group['uuid']];
unset($group['uuid']);
foreach ($group as $key => $value) {
$sum += $value;
}
$numbersArray[$cat][] = $sum;
}
But I get the error:
Unsupported operand types
Check if $numbersArray[$cat] is already set - if so, don’t add a new array element, but add the individual values to the existing array keys.
foreach ($numbersGroup as $group) {
$cat = $category[$group['uuid']];
unset($group['uuid']);
if(isset($numbersArray[$cat])) {
$numbersArray[$cat]['price'] += $group['price'];
$numbersArray[$cat]['discount'] += $group['discount'];
$numbersArray[$cat]['total'] += $group['total'];
}
else {
$numbersArray[$cat] = $group; // no [] here, because we want only a single element
}
}
Or, without an explicit if, using the ?? operator instead:
foreach ($numbersGroup as $group) {
$cat = $category[$group['uuid']];
$numbersArray[$cat]['price'] = ($numbersArray[$cat]['price'] ?? 0) + $group['price'];
$numbersArray[$cat]['discount'] = ($numbersArray[$cat]['discount'] ?? 0) + $group['discount'];
$numbersArray[$cat]['total'] = ($numbersArray[$cat]['total'] ?? 0) + $group['total'];
}
--
Edit:
I unfortunately I cannot write into my code "price", "discount" etc, because these values are always different, this cannot be hardcoded
Then loop over the keys you get from group, as you tried to with your initial code already:
foreach ($numbersGroup as $group) {
$cat = $category[$group['uuid']];
unset($group['uuid']);
foreach($group as $key => $value) {
$numbersArray[$cat][$key] = ($numbersArray[$cat][$key] ?? 0) + $value;
}
}
Can you try the below code
foreach ($numbersGroup as $group) {
$cat = $category[$group['uuid']];
if(!isset( $numbersArray[$cat][0]) )
$numbersArray[$cat][] = $group;
else{
// If index is known, you can use below code
/*$numbersArray[$cat][0]["price"]+= $group['price'];
$numbersArray[$cat][0]["discount"]+= $group['discount'];
$numbersArray[$cat][0]["total"]+= $group['total'];*/
// If index is not known
foreach($group as $key => $value){
if (is_numeric($value)) {
$numbersArray[$cat][0][$key]+= $group[$key];
}
}
}
}
Now I have added the case if array index is not known. We need a numeric checking before adding the values.
I hope this helps you :)
I am having three arrays
topicsSelected
relavantGroups
topicAssingned
$topicsSelected = [ "T-100","T-600"];
$relavantGroups = [
[ "id" => "G-001","name" => "3 A","active" => false ],
["id" => "G-002","name" => "3 B","active" => false]
];
$topicAssingned = [
"G-001" => [
"groupID" => "G-001",
"groupName" => "3 A",
"topics" => [
"T-100" => [
"topicID" => "T-100"
],
"T-200" => [
"topicID" => "T-200"
]
]
],
"G-002" => [
"groupID" => "G-002",
"groupName" => "3 B",
"topics" => [
"T-400" => [
"topicID" => "T-400"
],
"T-500" => [
"topicID" => "T-500"
]
]
],
];
$topicsSelected array values at least one value should present $topicAssingned means based on groupID, i have to push one value to $relavantGroups like disable : D suppose value not present means disable : A
Expected output:
[
"id" => "G-001",
"name" => "3 A",
"active" => false,
"disable" => "D"
],
[
"id" => "G-002",
"name" => "3 B",
"active" => false,
"disable" => "A"
]
<?php
$topicsSelected = [ "T-100","T-600"];
$relavantGroups = [
[ "id" => "G-001","name" => "3 A","active" => false ],
["id" => "G-002","name" => "3 B","active" => false]
];
$topicAssigned = [
"G-001" => [
"groupID" => "G-001",
"groupName" => "3 A",
"topics" => [
"T-100" => [
"topicID" => "T-100"
],
"T-200" => [
"topicID" => "T-200"
]
]
],
"G-002" => [
"groupID" => "G-002",
"groupName" => "3 B",
"topics" => [
"T-400" => [
"topicID" => "T-400"
],
"T-500" => [
"topicID" => "T-500"
]
]
],
];
$topic_selected_map = [];
foreach($topicsSelected as $each_topic){
$topic_selected_map[$each_topic] = true;
}
$relevant_group_map = [];
foreach($relavantGroups as $each_group){
$relevant_group_map[$each_group['id']] = $each_group;
}
$result = [];
foreach($topicAssigned as $each_assigned_topic){
if(!isset($relevant_group_map[$each_assigned_topic['groupID']])) continue;
$topics_not_found = true;
foreach($each_assigned_topic['topics'] as $each_topic => $topic_details){
if(isset($topic_selected_map[$each_topic])){
$topics_not_found = false;
break;
}
}
$result[] = [
'id' => $each_assigned_topic['groupID'],
'name' => $each_assigned_topic['groupName'],
'active' => $relevant_group_map[$each_assigned_topic['groupID']]['active'],
'disable' => ($topics_not_found === true ? 'A' : 'D')
];
}
print_r($result);
Output:
Array
(
[0] => Array
(
[id] => G-001
[name] => 3 A
[active] => false
[disable] => D
)
[1] => Array
(
[id] => G-002
[name] => 3 B
[active] => false
[disable] => A
)
)
First, make a map(associative array) of values of $topicsSelected. Same goes for $relavantGroups. This is to make the check more efficient. See more on Hash Table.
Now, iterate over $topicAssigned and then iterate over each group's topics inside it. Now, check if a topic exists inside $topicsSelected using a simple isset function. If yes, we disable them, else we don't.
It's not very clear what you are asking and the code is a bit weird but I'll give it a try.
First fix your array declaration - you should use => and not :;
You have to Iterate over the $relavantGroups and for each element iterate the $topicAssingned array. Then perform a simple comparison to see if the group Id is present and you are done!
Here is my solution (quick and dirty): You can see it here
foreach ($relavantGroups as &$g) {
$found = false;
foreach ($topicAssingned as $key => $assigned) {
if ($key === $g["id"] && is_array($assigned["topics"])) {
foreach ($assigned["topics"] as $topic) {
if (in_array($topic["topicID"], $topicsSelected)) {
$found = true;
break;
}
}
}
}
$g["disable"] = $found ? "D" : "A";
}
var_dump($relavantGroups);
Updated the solution - note that I'm using in_array() to determine if the topicID is present. That mean that any value that is in the $topicsSelected array will affect the result.
Hope I helped.
This will output (based one your example):
array(2) {
[0]=> array(4) {
["id"]=> string(5) "G-001"
["name"]=> string(3) "3 A"
["active"]=> bool(false)
["disable"]=> string(1) "D"
}
[1]=> array(4) {
["id"]=> string(5) "G-002"
["name"]=> string(3) "3 B"
["active"]=> bool(false)
["disable"]=> string(1) "A"
}
}
This shouldn't be confusing me as much as it is but I am looking to turn this:
array:3 [▼
"subject" => array:2 [▼
0 => "math"
1 => "english"
]
"grade" => array:2 [▼
0 => "a"
1 => "b"
]
"received" => array:2 [▼
0 => "2017"
1 => "2016"
]
]
into this:
array:2 [▼
"0" => array:3 [▼
"subject" => "math"
"grade" => "a"
"received" => "2017"
]
"1" => array:3 [▼
"subject" => "english"
"grade" => "b"
"received" => "2016"
]
]
Tried looping through in a couple different ways but never seem to get the result I am looking for, any help would be much appreciated!
$keys = array_keys($array);
$result = array_map(
function (...$values) use ($keys) { return array_combine($keys, $values); },
...array_values($array)
);
Which is essentially this, but less repetitive:
array_map(
function ($subject, $grade, $received) {
return [
'subject' => $subject,
'grade' => $grade,
'received' => $received
];
},
$array['subject'],
$array['grade'],
$array['received']
)
See the manual for array_map and ... for more explanation.
simple Version:
$arr1 = array(...);
$arr2 = array();
foreach ($arr1 as $k => $v) {
foreach ($v as $x => $y) {
$arr2[$x][$k] = $y;
}
}
But you should add conditions, if the array element not exists, create it, or you may get Errors, depending on your PHP configuration.
This question already has answers here:
Merge two 2d arrays by shared column value
(6 answers)
Closed 5 months ago.
i want to join two arrays where 1 key should join them.
array:1 [
0 => array:2 [
"MONAT" => "AUG"
"MAIL_CNT" => "2"
]
1 => array:2 [
"MONAT" => "JUL"
"MAIL_CNT" => "1"
]
]
array:2 [
0 => array:2 [
"MONAT" => "AUG"
"ORDER_CNT" => "18"
]
1 => array:2 [
"MONAT" => "JUL"
"ORDER_CNT" => "1"
]
]
The result should be something like
array:1 [
0 => array:2 [
"MONAT" => "AUG"
"MAIL_CNT" => "2"
"ORDER_CNT" => "18"
]
1 => array:2 [
"MONAT" => "JUL"
"MAIL_CNT" => "1"
"ORDER_CNT" => "1"
]
]
I cant figure out what to do.
Thanks in advance and greetings !
use array_replace_recursive
$array = array_replace_recursive($a1, $a2);
you should use php array_replace_recursive() for this
$arr1=array(
0 =>array(
"MONAT" => "AUG",
"MAIL_CNT" => "2"
),
1 => array(
"MONAT" => "JUL",
"MAIL_CNT" => "1"
)
);
$arr2=array(
0 => array(
"MONAT" => "AUG",
"ORDER_CNT" => "18"
),
1 => array(
"MONAT" => "JUL",
"ORDER_CNT" => "1"
)
);
$array = array_replace_recursive($arr1, $arr2);
echo"<pre>"; print_r($array);
$mergedArray = array();
foreach( $arr1 as $key => $row) {
$mergedArray[$key] = array_merge($arr2[$key], $row)
}
hope this helps
1st : simple use array_merge
2nd : & means it is passed by reference instead of value
foreach( $array1 as $key => &$val) {
$val = array_merge($val,$array2[$key]);
}
print_r($array1);
Note : Above code will work only if both array count is same otherwise it will throw the error .
I have an array that looks like this
"name" => array:3 [
1 => "Hello"
4 => "Test"
21 => "Test2"
]
"runkm" => array:3 [
1 => "100.00"
4 => "1000.00"
21 => "2000.00"
]
"active" => array:3 [
1 => "1"
4 => "0"
21 => "0"
]
Can i somehow combine the matching keys with a PHP function so that the array would look like this instead
1 => array:3 [
name => "Hello"
runkm => "100.00"
active => "1"
]
4 => array:3 [
name => "Test"
runkm => "1000.00"
active => "0"
]
21 => array:3 [
name => "Test2"
runkm => "2000.00"
active => "0"
]
EDIT: Thanks for all the answers guys. What i was really looking for was a PHP built in function for this, which i probably should have been more clear about.
$newArr=array();
foreach($array1 as $key => $value){
$newArr[$key]=>array(
'name' =>$value[$key];
'runkm' =>$array2[$key];
'active'=>$array3[$key];
);
}
this is how you make a new array and then print the $newArr and check you get what you want or not? Good Luck!
<?php
$resultarr = array();
for($i=0;$i<count($sourcearr['name']);$i++) {
$resultarr[] = array('name'=>$sourcearr['name'][$i], 'runkm'=>$sourcearr['runkm'][$i], 'active'=>$sourcearr['active'][$i]);
}
This works well. And also, doesn't use hard coded keys.
<?php
$arr = [
"name" => [
1 => "Hello",
4 => "Test",
21 => "Test2"
],
"runkm" => [
1 => "100.00",
4 => "1000.00",
21 => "2000.00"
],
"active" => [
1 => "1",
4 => "0",
21 => "0"
]
];
// Pass the array to this function
function extractData($arr){
$newarr = array();
foreach ($arr as $key => $value) {
foreach($value as $k => $v) {
if(!isset($newarr[$k]))
$newarr[$k] = array();
$newarr[$k][$key] = $v;
}
}
return $newarr;
}
print_r(extractData($arr));
?>
I'm not sure if there's a function that does that in PHP but maybe you can try this
$arr1 = array(
"name" => array(
1 => "hello",
4 => "test",
21 => "test2",
),
"runKm" => array(
1 => "100",
4 => "200",
21 => "300",
),
"active" => array(
1 => "1",
4 => "0",
21 => "0",
),
);
// declare another that will hold the new structure of the array
$nArr = array();
foreach($arr1 as $key => $val) {
foreach($val as $sub_key => $sub_val) {
$nArr[$sub_key][$key] = $sub_val;
}
}
what this does is simply loop thru each array and its values and assign it to another array which is the $nArr. I hope it helps.