Restructure multidimensional array of column data into multidimensional array of row data
As Kris Roofe stated in his deleted answer, array_column
is indeed a more elegant way. Just be sure to put it into some kind of a foreach
loop, similar to what Sahil Gulati showed you. For example, like this:
$result = array();
foreach($where['id'] as $k => $v)
{
$result[] = array_column($where, $k);
}
The var_dump
output of $result
is exactly what you're looking for
array(3) {
[0]=>
array(2) {
[0]=>
int(12)
[1]=>
string(10) "1999-06-12"
}
[1]=>
array(2) {
[0]=>
int(13)
[1]=>
string(10) "2000-03-21"
}
[2]=>
array(2) {
[0]=>
int(14)
[1]=>
string(10) "2006-09-31"
}
}
Group rows of data by a column value and restructure into an associative multi-dimensionsl array
You don't need to pre-extract the unique years nor use conditions within nested loops. Just push the data into the result set using temporary first-level keys, then remove the temporary keys when finished looping.
This ensures unique years, but allows names to be duplicated.
Code: (Demo)
$arr = [
["year" => 1921, "name" => "bob"],
["year" => 1944, "name" => "steve"],
["year" => 1944, "name" => "doug"],
["year" => 1921, "name" => "jim"],
];
foreach ($arr as $item) {
$result[$item['year']]['year'] = $item['year'];
$result[$item['year']]['names'][] = ['name' => $item['name']];
}
echo json_encode(
['data' => array_values($result)],
JSON_PRETTY_PRINT // for better visualization
);
Output:
{
"data": [
{
"year": 1921,
"names": [
{
"name": "bob"
},
{
"name": "jim"
}
]
},
{
"year": 1944,
"names": [
{
"name": "steve"
},
{
"name": "doug"
}
]
}
]
}
Convert DataFrame to multidimensional array following a format
Can use a normal for loop here this works but if the number of rows are very large it becomes very slow.
new_list = []
for i in range(len(df1)):
new_list.append([[df1["latitude_1"][i],df1["longitude_1"][i]],[df1["latitude_2"][i],df1["longitude_2"][i]]])
This will faster than using the for loop
new_list = df.values.ravel()
new_list.reshape(len(df),2,2)
Reshape 2x6 array into 3x2x2, row-wise
EDIT:
The better method is aperm(array(data, c(2, 2, 3)))
. Thanks @smci for the link.
Original solution:
I get different data with that seed, but you can use matrix
and lapply
to make each row a two-column matrix, then abind
to bind into one array.
set.seed(10)
data <- array(rexp(12), dim=c(2,6))
data
#
# [,1] [,2] [,3] [,4] [,5] [,6]
# [1,] 0.01495641 0.7521589 0.2316586 2.3276229 1.2883101 0.4265298
# [2,] 0.92022120 1.5750419 1.0866730 0.7291238 0.6722683 1.1154219
library(abind)
abind(lapply(split(data, row(data)), matrix, ncol = 2, byrow = T)
, along = 3)
# , , 1
#
# [,1] [,2]
# [1,] 0.01495641 0.7521589
# [2,] 0.23165862 2.3276229
# [3,] 1.28831010 0.4265298
#
# , , 2
#
# [,1] [,2]
# [1,] 0.9202212 1.5750419
# [2,] 1.0866730 0.7291238
# [3,] 0.6722683 1.1154219
With pipes
library(magrittr)
data %>%
split(row(.)) %>%
lapply(matrix, ncol = 2, byrow = T) %>%
abind(along = 3)
Here's an option that is much faster and requires no packages. I don't think it's very clear though. Not sure how to write it more clearly.
array(unlist(data)[order(rep(c(1, 3, 2, 4), 3))], dim = c(3, 2, 2))
Maybe this?
array(unlist(data) %>% .[order(!seq_along(.) %% 2
, !seq_along(.) %% 4)]
, dim = c(3, 2, 2))
How to convert a multidimensional array into a single line array in PHP?
The variadiac php5.6+ version: (Offers the added benefits of not breaking on missing values and inserting null
where values are missing.)
Code: (Demo)
var_export(array_map(function(){return implode(',',func_get_args());},...$text));
The non-variadic version:
Code: (Demo)
foreach($text as $i=>$v){
$result[]=implode(',',array_column($text,$i));
}
var_export($result);
Input:
$text = [
['001','002','003'],
['America','Japan','South Korea'],
['Washington DC','Tokyo','Seoul']
];
Output from either method:
array (
0 => '001,America,Washington DC',
1 => '002,Japan,Tokyo',
2 => '003,South Korea,Seoul',
)
Nearly exact duplicate page: Combining array inside multidimensional array with same key
PHP combine the value of one array with value of second array into a third custom array
Try the following form inputs instead:
<input type="checkbox" name="data[0][code]" value="FDS">
<input id="flexDeliveryEmailInput" type="text" name="data[0][info]">
<input id="flexDeliverySMS" type="checkbox" name="data[1][code]" value="FSS">
<input type="text" name="data[1][info]">
This will provide the merged array as you want it.
Related Topics
Warning: Domdocument::Loadhtml(): Htmlparseentityref: Expecting ';' in Entity,
How to Prevent the "Confirm Form Resubmission" Dialog
PHP: Sort and Count Instances of Words in a Given String
Parentheses Altering Semantics of Function Call Result
What Are PHP Nested Functions For
PHP Sessions Timing Out Too Quickly
How to Get the Sqlsrv Extension to Work With PHP, Since Mssql Is Deprecated
Set Cookie Wih Js, Read With PHP Problem
How to Use Arrays in Curl Post Requests
How to Make Dot Match Newline Characters Using Regular Expressions
How to Make This Preg_Match Case Insensitive
Sort and Display Directory List Alphabetically Using Opendir() in PHP