Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I would like to order $ArrayToOrder according to column SecondArrayField2 in $SecondArray, where the link between the two arrays are Field_3 (in $ArrayToOrder) and SecondArrayField1 in $SecondArray.
$ArrayToOrder=Array
(
[0] => Array
(
[Field_1] => 13
[Field_2] => 15
[Field_3] => 3
)
[1] => Array
(
[Field_1] => 25
[Field_2] => 17
[Field_3] => 2
)
[2] => Array
(
[Field_1] => 121
[Field_2] => 20
[Field_3] => 11
)
)
$SecondArray=Array
(
[0] => Array
(
[SecondArrayField1] => 11
[SecondArrayField2] => Bruce
)
[1] => Array
(
[SecondArrayField1] => 3
[SecondArrayField2] => Arthur
)
[2] => Array
(
[SecondArrayField1] => 2
[SecondArrayField2] => Mary
)
)
Desired result as follows:
$ArrayToOrder=Array
(
[0] => Array
(
[Field_1] => 13
[Field_2] => 15
[Field_3] => 3 //(Arthur)
)
[1] => Array
(
[Field_1] => 121
[Field_2] => 20
[Field_3] => 11 //(Bruce)
)
[2] => Array
(
[Field_1] => 25
[Field_2] => 17
[Field_3] => 2 //(Mary)
)
)
Here is snippet you can use,
// first fetching key as SecondArrayField2 and SecondArrayField1 as value
$Field_3 = array_column($SecondArray, "SecondArrayField1","SecondArrayField2");
// sort by key alphabetically
ksort($Field_3);
//
$sorted = array_values(array_map(function($v) use ($ArrayToOrder) {
// first fetched Field_3 matching with current value of $Field_3 in the order
// get the index of matching Field_3
// save it to sorted array its sub array
return $ArrayToOrder[array_search($v, array_column($ArrayToOrder,'Field_3'))];
}, $Field_3));
print_r($sorted);die;
Demo.
Output:
Array
(
[0] => Array
(
[Field_1] => 13
[Field_2] => 15
[Field_3] => 3 //(Arthur)
)
[1] => Array
(
[Field_1] => 121
[Field_2] => 20
[Field_3] => 11 // (Bruce)
)
[2] => Array
(
[Field_1] => 25
[Field_2] => 17
[Field_3] => 2 // (Mary)
)
)
Related
Hello & thanks for your interest
I do have two arrays:
[A] -from the mysql query of one database on server1- the
$postings_array - a SELECT of all postings of a discussion-thread
(based on the thread's id)
[B] -from the mysql query of an other database on server2 - the
$usersdata_array - a SELECT of all postings of a discussion-thread
(based on the thread's id)
This means:
in [A] there are many postings-sub-arrays and in [B] one or more
userdata-sub-arrays.
both arrays always do include a key named usrsID in each of their
subarrays.
I need to extend the Sub-Arrays in $postings_array [A]
by merging them
with the Sub-Arrays of the $usersdata_array [B]
based on WHERE the VALUE of the usrsID KEY in the sub-array[A] is EQUAL to the usrsID KEY in the sub-array[B].
EXAMPLE:
Array [A]:
(
[0] => Array
(
[ID] => 5
[usrsID] => 3
[tid] => 19
[txtid] => 22
)
[1] => Array
(
[ID] => 6
[usrsID] => 1
[tid] => 19
[txtid] => 23
)
[2] => Array
(
[ID] => 7
[usrsID] => 2
[tid] => 19
[txtid] => 24
)
[3] => Array
(
[ID] => 8
[usrsID] => 1
[tid] => 19
[txtid] => 25
)
)
--
Array [B]:
(
[0] => Array
(
[id] => 1
[usrsID] => 1
[avatarID] => 1
)
[1] => Array
(
[id] => 2
[usrsID] => 2
[avatarID] => 3
)
[2] => Array
(
[id] => 3
[usrsID] => 3
[avatarID] => 22
)
)
needed result (the by [B] extended [A] for the example above):
Array [A_extended]:
(
[0] => Array
(
[ID] => 5
[usrsID] => 3
[tid] => 19
[txtid] => 22
[id] => 3
[avatarID] => 22
)
[1] => Array
(
[ID] => 6
[usrsID] => 1
[tid] => 19
[txtid] => 23
[id] => 1
[avatarID] => 1
)
[2] => Array
(
[ID] => 7
[usrsID] => 2
[tid] => 19
[txtid] => 24
[id] => 2
[avatarID] => 3
)
[3] => Array
(
[ID] => 8
[usrsID] => 1
[tid] => 19
[txtid] => 25
[id] => 1
[avatarID] => 1
)
)
... I think, it's a common problem so there should be a best-practice around (may be in one inbuild php function or a combination of two or three of them) - and I do not have to reinvent the wheel.
At least, I hope so...
else, my approach would be
check the amounts of iterations (= the subarrays found in the $usersdata_array [B] )
iterate over the outerHaystack and trigger a function when $needle was found in innerHaystack
perform merge via checkSubArrayfunc
Approach,
with hayStackArray = complete [A]Array;
needle = $usrsID value of [B] Sub-Array:
function checkSubArrayfunc($hayStackSubArray, $needle, $toMergeSubArray) {
if (in_array(array('$hayStackSubArray'), $needle)) {
array_merge_recursive($hayStackSubArray, $toMergeSubArray);
}
}
Try this:
foreach($arr_b as $b_item) {
foreach($arr_a as $key => &$a_item) {
if ($b_item['usrsID'] == $a_item['usrsID']) {
$a_item['id'] = $b_item['usrsID'];
$a_item['avatarID'] = $b_item['avatarID'];
}
}
}
Your output of $_arr_a will be:
Array
(
[0] => Array
(
[ID] => 5
[usrsID] => 3
[tid] => 19
[txtid] => 22
[id] => 3
[avatarID] => 22
)
[1] => Array
(
[ID] => 6
[usrsID] => 1
[tid] => 19
[txtid] => 23
[id] => 1
[avatarID] => 1
)
[2] => Array
(
[ID] => 7
[usrsID] => 2
[tid] => 19
[txtid] => 24
[id] => 2
[avatarID] => 3
)
[3] => Array
(
[ID] => 8
[usrsID] => 1
[tid] => 19
[txtid] => 25
[id] => 1
[avatarID] => 1
)
)
At first take an empty array for store marged array. then traversed in both array. if the userID are be same in both the array of element then marge these array and push in margeArr.
$margeArr = [];
foreach($Array_A as $a){
foreach($Array_B as $b){
if($a['usrsID'] == $b['usrsID']){
array_push($margeArr,array_merge($a,$b));
}
}
}
print_r($margeArr);
Comment by the questionaire:
It's a great solution - it really meets the requirements described in my question and merges the to be marged Array with the key-value-pairs of the "to be injected"-Array.
But I prefere the bestprogrammersinintheworld's solution, where I can rename the keys "en passant / on-the-fly":
foreach($arr_b as $b_item) {
foreach($arr_a as $key => &$a_item) {
if ($b_item['usrsID'] == $a_item['usrsID']) {
$a_item['myNewKeyName1'] = $b_item['usrsID'];
$a_item['myNewKeyName2'] = $b_item['avatarID'];
}
}
}
print("<pre>".print_r($arr_a,true)."</pre>");
Sorting my advice from best to worst...
Joining this data should be done before PHP is necessary. Depending on the location of the two sources, this may be trivial, but JOINing via SQL is the best, most direct, most professional option. These links may be helpful:
access two different databases on different servers in the same query
Joining Tables from different Database
In lieu of option 1, declare and leverage a lookup array (in PHP) which would have the identifying column as its first level keys. Then you don't need to nest another loop to relate the two data sets.
$lookup = array_column($arrayB, null, 'usrsID');
foreach ($arrayA as $row) {
$result[] = $row + ($lookup[$row['usrsID']] ?? []);
}
The worst option which I do NOT recommend is writing a nested loop with a condition inside of it. All previous answers are doing this -- and slowing down an already inefficient approach, they don't even break inside the condition block.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
Array output generated from database values.
Array ( [0] => Array ( [seldate] => 2019-04-28 [count] => 268 )
[1] => Array ( [seldate] => 2019-04-29 [count] => 366 )
[2] => Array ( [seldate] => 2019-04-30 [count] => 85 )
[3] => Array ( [seldate] => 2019-04-28 [count] => 93 )
[4] => Array ( [seldate] => 2019-04-29 [count] => 82 )
[5] => Array ( [seldate] => 2019-04-30 [count] => 31 )
[6] => Array ( [seldate] => 2019-04-28 [count] => 44 )
[7] => Array ( [seldate] => 2019-04-29 [count] => 44 )
[8] => Array ( [seldate] => 2019-04-30 [count] => 22 ) )
I need to create below
string output from above array for google LineChart.
"['2019-04-28', 268, 93, 44],
['2019-04-29', 366, 82, 44],
['2019-04-30', 85, 31, 22]"
Please help to create PHP Code logic.
First prepare your array as key being the date and the values being the values.
Then loop it again and write the lines to a new array with the imploded values.
Lastly output the lines with implode on comma and new line.
foreach($rows as $r){
$dates[$r['seldate']][] = $r['count'];
}
foreach($dates as $date => $vals){
$lines[] = "['" . $date . "', " . implode(", ", $vals) . "]";
}
echo implode(",\n", $lines);
Output:
['2019-04-28', 268, 93],
['2019-04-29', 366],
['2019-04-30', 85]
https://3v4l.org/14smE
You can traverse array by using array_walk as below
$result = [];
array_walk($arr, function($item) use(&$result){
if(empty($result[$item['seldate']])){ // if empty add date and count for initialisation
$result[$item['seldate']] = [$item['seldate'], $item['count']];
}else{
$result[$item['seldate']][] = $item['count']; // just append value to same key as date as we are grouping it by date
}
});
$result = array_values($result); // to remove date keys
print_r($result);
Output
Array
(
[0] => Array
(
[0] => 2019-04-28
[1] => 268
[2] => 93
[3] => 44
)
[1] => Array
(
[0] => 2019-04-29
[1] => 366
[2] => 82
[3] => 44
)
[2] => Array
(
[0] => 2019-04-30
[1] => 85
[2] => 31
[3] => 22
)
)
Demo
Note: If you want to use this data for linechart, json_encode above output.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I have a PHP array like the following one and I would like to combine a multi array to one array:
Array
(
[0] => ADB_DW2017
[1] => LM9
[2] => MS_OF2013
)
Array
(
[0] => NK
[1] => PV
[2] => NK
)
Array
(
[0] => 15
[1] => 25
[2] => 10
)
Array
(
[0] => 250
[1] => 111
[2] => 150
)
Array
(
[0] => 450
[1] => 123
[2] => 250
)
Array
(
[0] => 0
[1] => Mien thue
[2] => 5
)
Array
(
[0] => 200
[1] => 12
[2] => 100
)
Array
(
[0] => 6.750
[1] => 3.075
[2] => 2.500
)
I want to combine like this, with the highest performance :
Array
(
[ADB_DW2017]=>array([suppiler]=>NK
[min_pro]=>15
[max_pro]=>250
[avg_pro]=>450
[tax]=>0
[com]=>200
[sum]=>6.750
)
)
My question is : How to combine a multi array to one array in PHP with the highest performance ?
I assume array names are $first_array,$second_array,...... (so change varabile names accordingly).
Do like below:-
$final_array = array();
foreach ($first_array as $key=> $arr){
$final_array[$arr] =array(
'suppiler'=>(isset($second_array[$key]))? $second_array[$key]: '',
'min_pro'=>(isset($third_array[$key]))? $third_array[$key]: 0,
'max_pro'=>(isset($fourth_array[$key]))? $fourth_array[$key]: 0,
'avg_pro'=>(isset($fifth_array[$key]))? $fifth_array[$key]: 0,
'tax'=>(isset($sixth_array[$key]))? $sixth_array[$key]: '',
'com'=>(isset($seventh_array[$key]))? $seventh_array[$key]: 0,
'sum'=>(isset($eigth_array[$key]))? $eigth_array[$key]: 0
);
}
echo "<pre/>";print_r($final_array);
Output:-https://eval.in/829938
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I have one array I want that data belong to same day will appear on one index like in the below array I have same the date in 1 and 2 index so the result array should be like my ewault array so that data belonging to the same date will show up on same index. How can I do this?
My Array:
Array
(
[0] => Array
(
[pkMessageID] => 6
[fkPostID] => 4
[messageSenderID] => 2
[messageRecieverID] => 19
[messageBody] => Nice
[messageStatus] => 1
[DateOnly] => 2015-07-07
[messageDateAdded] => 2015-07-07 16:20:58
)
[1] => Array
(
[pkMessageID] => 5
[fkPostID] => 4
[messageSenderID] => 19
[messageRecieverID] => 2
[messageBody] => Hi I am good how r u
[messageStatus] => 1
[DateOnly] => 2015-07-06
[messageDateAdded] => 2015-07-06 16:14:05
)
[2] => Array
(
[pkMessageID] => 4
[fkPostID] => 4
[messageSenderID] => 2
[messageRecieverID] => 19
[messageBody] => Hello akhilesh how r u
[messageStatus] => 1
[DateOnly] => 2015-07-06
[messageDateAdded] => 2015-07-06 16:12:22
)
)
However, the result array should be:
Array
(
[0] => Array
(
[pkMessageID] => 6
[fkPostID] => 4
[messageSenderID] => 2
[messageRecieverID] => 19
[messageBody] => Nice
[messageStatus] => 1
[DateOnly] => 2015-07-07
[messageDateAdded] => 2015-07-07 16:20:58
)
[1] => Array
(
[0] => Array
(
[pkMessageID] => 5
[fkPostID] => 4
[messageSenderID] => 19
[messageRecieverID] => 2
[messageBody] => Hi I am good how r u
[messageStatus] => 1
[DateOnly] => 2015-07-06
[messageDateAdded] => 2015-07-06 16:14:05
)
[1] => Array
(
[pkMessageID] => 4
[fkPostID] => 4
[messageSenderID] => 2
[messageRecieverID] => 19
[messageBody] => Hello akhilesh how r u
[messageStatus] => 1
[DateOnly] => 2015-07-06
[messageDateAdded] => 2015-07-06 16:12:22
)
)
)
This can be done using the following:
$out = array();
foreach($input as $data)
{
if( ! is_array($out[$data['DateOnly']])){
$out[$data['DateOnly']] = array();
}
$out[$data['DateOnly']][] = $data;
}
I haven't the code, but i hope you get the idea. Simply use the date as an index in your array. So the result will be along the lines of.
[2015-7-6] => Array ( [0] => Array( DateOnly => 2015-7-6, ..))
[2015-7-7] => Array ( [0] => Array( DateOnly => 2015-7-7, .. ), [1] => Array(DateOnly => 2015-7-7 , .. ))
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Array
(
[0] => Array
(
[religion] => Christian
[emp_count] => 4
[b_name] => tripura
[branch_id] => 7
)
[1] => Array
(
[religion] => Christian
[emp_count] => 2
[b_name] => Tirunelveli
[branch_id] => 10
)
[2] => Array
(
[religion] => Christian
[emp_count] => 4
[b_name] => Madurai
[branch_id] => 12
)
[3] => Array
(
[religion] => Hindu
[emp_count] => 3
[b_name] => tripura
[branch_id] => 7
)
[4] => Array
(
[religion] => Hindu
[emp_count] => 4
[b_name] => Tirunelveli
[branch_id] => 10
)
[5] => Array
(
[religion] =>
[emp_count] => 0
[b_name] =>
[branch_id] =>
)
[6] => Array
(
[religion] =>
[emp_count] => 0
[b_name] =>
[branch_id] =>
)
[7] => Array
(
[religion] => Muslim
[emp_count] => 1
[b_name] => Tirunelveli
[branch_id] => 10
)
[8] => Array
(
[religion] =>
[emp_count] => 0
[b_name] =>
[branch_id] =>
)
)
i need to group the array by the same key and value and create a json data with the grouped array.
For Eg: i need to display it as
{
name : 'Christian',
data :[4,2,4]
},
{name:'Hindu',
data:[3,2,1]
} ....
Give this a go!
Create your own array
Loop through your current array ($arrArray)
Group elements, by adding them to $arrGrouped
The code
$arrGrouped = array();
foreach($arrArray as $arrElement) {
if( array_key_exists($arrElement['religion'], $arrGrouped) ) {
$arrGrouped[$arrElement['religion']] += $arrElement['emp_count'];
} else {
$arrGrouped[$arrElement['religion']] = $arrElement['emp_count'];
}
}
echo '<pre>'. json_encode($arrGrouped, true) .'</pre>';
I would do this in two steps:
Group the same religion together and gather the counts
Map the result into the final data array
So:
$result = array_reduce($array, function(&$result, $current) {
$result[$current['religion']][] = $current['emp_count'];
return $result;
}, []);
$data = [];
foreach ($result as $religion => $emp_counts) {
$data[] = [
'name' => $religion,
'data' => $emp_counts,
];
}
echo json_encode($data);
See: array_reduce() json_encode()