Return single column from a multi-dimensional array
Quite simple:
$input = array(
array(
'tag_name' => 'google'
),
array(
'tag_name' => 'technology'
)
);
echo implode(', ', array_map(function ($entry) {
return $entry['tag_name'];
}, $input));
http://3v4l.org/ltBZ0
and new in php v5.5.0, array_column
:
echo implode(', ', array_column($input, 'tag_name'));
C extract specific column from multi-dimensional array using pointers only
You are not modifying the offset to compensate for the number of columns in your matrix. In memory, the multidimensional array is flat (i.e. 1-dimensional), and it's up to your program to use an appropriate step size to skip over each row.
Since you seem to want your function to operate on arbitrary dimensions, then you must pass the actual number of columns as a parameter (e.g. num_cols
), and change your code as follows:
value = info[row_i * num_cols + column_dimension];
single_dimension[row_i] = value;
Get column from a two dimensional array
You have to loop through each element in the 2d-array, and get the nth column.
function getCol(matrix, col){
var column = [];
for(var i=0; i<matrix.length; i++){
column.push(matrix[i][col]);
}
return column;
}
var array = [new Array(20), new Array(20), new Array(20)]; //..your 3x20 array
getCol(array, 0); //Get first column
Extracting a column from a specific multi-dimensional array in C#
You can flatten 2d array using .Cast<int>()
and then take first row using .Take(2)
:
const int arraySize = 2;
var resultat = (res[0] as int[,]).Cast<int>().Take(arraySize).ToArray();
In general case for an arbitrary row index you can use .Skip(arraySize * rowIndex)
If it is too slow for you, you may try Buffer.BlockCopy
:
const int rowSize = 2;
const int intSize = 4;
int[] resultat = new int[rowSize];
Buffer.BlockCopy(res[0], 0, resultat, 0, intSize * rowSize);
In general case it would be
const int intSize = 4; // Size of integer type in bytes
int[,] matrix = res[0];
int rowSize = matrix.GetLength(1); // Get size of second 2d-array dimension
int rowIndex = 0; // Index of a row you want to extract
int[] resultat = new int[rowSize];
Buffer.BlockCopy(res[0], // Copy source
rowSize * intSize * rowIndex, // Source offset in bytes
resultat, // Copy destination
0, // Destination offset
intSize * rowSize); // The number of bytes to copy
Buffer.BlockCopy documentation
How to get a complete row or column from 2D array in C#
You can optimise it for getting rows by using Buffer.BlockCopy()
, but to get a column you'll have to loop. Buffer.BlockCopy()
ultimately uses a processor instruction to copy a block of memory, so it is pretty fast.
It's convenient to put the code into an extension method to make it easier to call. Note that Buffer.BlockCopy()
can only be used on arrays of primitive types, i.e. int
, double
, char
etc. This does NOT include string
.
Here's a compilable example:
using System;
using System.Linq;
using System.Runtime.InteropServices;
namespace ConsoleApplication4
{
public static class Program
{
private static void Main()
{
var array = new [,]
{
{0.1, 0.2, 0.3, 0.4, 0.5},
{1.1, 1.2, 1.3, 1.4, 1.5},
{2.1, 2.2, 2.3, 2.4, 2.5},
{3.1, 3.2, 3.3, 3.4, 3.5},
};
var row = array.GetRow(2);
// This prints 2.1, 2.2, 2.3, 2.4, 2.5
Console.WriteLine(string.Join(", ", row.Select(element => element.ToString())));
}
}
public static class ArrayExt
{
public static T[] GetRow<T>(this T[,] array, int row)
{
if (!typeof(T).IsPrimitive)
throw new InvalidOperationException("Not supported for managed types.");
if (array == null)
throw new ArgumentNullException("array");
int cols = array.GetUpperBound(1) + 1;
T[] result = new T[cols];
int size;
if (typeof(T) == typeof(bool))
size = 1;
else if (typeof(T) == typeof(char))
size = 2;
else
size = Marshal.SizeOf<T>();
Buffer.BlockCopy(array, row*cols*size, result, 0, cols*size);
return result;
}
}
}
How do I return such an multi-dimensional array?
You can use streams to create such an array:
public static int[][] labelPath(int n, int[][] points) {
// create a new empty 2d array filled with zeros
int[][] matrix = new int[n][n];
// set all array elements to 'n'
Arrays.setAll(matrix, row -> {
Arrays.fill(matrix[row], n);
return matrix[row];
});
// iterate over the points array and set the corresponding elements to '-1'
Arrays.stream(points).forEach(row -> matrix[row[1]][row[0]] = -1);
return matrix;
}
// test
public static void main(String[] args) {
int n = 4;
int[][] data0 = {{3, 0}, {0, 1}, {2, 2}};
int[][] matrix = labelPath(n, data0);
// output
Arrays.stream(matrix).map(Arrays::toString).forEach(System.out::println);
}
[4, 4, 4, -1]
[-1, 4, 4, 4]
[4, 4, -1, 4]
[4, 4, 4, 4]
See also: What is the most efficient way to create a 2d string array of initally repetitive data?
How to get multidimensional array grouped by multiple columns in PHP from single MySQL table?
First, I would recommend you stick with your code solution. Run a simple SQL query, and process the results, collating them into the nested array structure you want. You already have that coded, it's easier to debug and easier to change in the future if you need to change it.
I've implemented something like you describe, to create a nested structure in an SQL query. It was pretty hard, and the SQL query was complex enough that it will be a maintenance problem in the future if we ever need to modify the contents of the nested structure.
The solution I used in the SQL query was to use multiple levels of derived table subqueries, and generate aggregate JSON results at each level using JSON functions. This requires using MySQL 5.7 or later, because these JSON functions are not implemented in earlier versions of MySQL.
Demo test data:
create table if not exists mytable ( id int primary key, survey_type varchar(20), guid char(36), guid_type varchar(20), table_id int, created_at datetime );
insert into mytable values
(2 ,'TYPE 1','6C7251E3-2151-4754-A413-51899FAAF6C2','question','2','2022-03-20 16:14:09'),
(3 ,'TYPE 1','EF5AFA93-C74D-4920-A13A-17A9B43239CD','question','3','2022-03-20 16:14:09'),
(4 ,'TYPE 1','5C059148-94BE-4225-B5C2-551A81B65F16','question','4','2022-03-20 16:14:09'),
(5 ,'TYPE 1','356B8A5C-1072-47A5-A508-D9BDCBA92CCC','answer','5','2022-03-20 16:14:09'),
(6 ,'TYPE 1','E0CE4C26-7ABD-4162-9C8C-B4DD540AE268','answer','6','2022-03-20 16:14:09'),
(7 ,'TYPE 1','BFBC50FC-892D-43E9-A235-D76E0D0BEF29','answer','7','2022-03-20 16:14:09'),
(8 ,'TYPE 2','B9DCC5C1-CBFB-4589-98EF-4524F3958968','survey','8','2022-03-20 16:14:09'),
(9 ,'TYPE 2','C98FBFF9-6FE3-414E-BB14-08EDC8281E66','survey','9','2022-03-20 16:14:09'),
(10 ,'TYPE 2','8A780B6E-EAE0-47D6-9D05-F52B795AE617','question','10','2022-03-20 16:14:09'),
(11 ,'TYPE 2','E3818D30-BB69-4F03-B56D-B31691F8007E','question','11','2022-03-20 16:14:09'),
(12 ,'TYPE 2','24C81BEF-BFCE-4964-AB01-F3579251313D','answer','12','2022-03-20 16:14:09'),
(13 ,'TYPE 3','59381701-AFBC-48F8-AECE-DB3702EE2B15','answer','13','2022-03-20 16:14:09'),
(14 ,'TYPE 3','7F4AC694-74DC-4BEA-ACFB-D8F070769FEE','answer','14','2022-03-20 16:14:09'),
(15 ,'TYPE 3','B5C405B9-BA7E-471A-87DD-B69D9757276F','survey','15','2022-03-20 16:14:09');
Example query:
select json_pretty(json_objectagg(survey_type, g)) as j
from (
select survey_type, json_objectagg(guid_type, t) as g
from (
select survey_type, guid_type, json_objectagg(table_id, guid) as t
from mytable
group by survey_type, guid_type
) as t
group by survey_type
) as g;
Output:
{
"TYPE 1": {
"answer": {
"5": "356B8A5C-1072-47A5-A508-D9BDCBA92CCC",
"6": "E0CE4C26-7ABD-4162-9C8C-B4DD540AE268",
"7": "BFBC50FC-892D-43E9-A235-D76E0D0BEF29"
},
"question": {
"2": "6C7251E3-2151-4754-A413-51899FAAF6C2",
"3": "EF5AFA93-C74D-4920-A13A-17A9B43239CD",
"4": "5C059148-94BE-4225-B5C2-551A81B65F16"
}
},
"TYPE 2": {
"answer": {
"12": "24C81BEF-BFCE-4964-AB01-F3579251313D"
},
"survey": {
"8": "B9DCC5C1-CBFB-4589-98EF-4524F3958968",
"9": "C98FBFF9-6FE3-414E-BB14-08EDC8281E66"
},
"question": {
"10": "8A780B6E-EAE0-47D6-9D05-F52B795AE617",
"11": "E3818D30-BB69-4F03-B56D-B31691F8007E"
}
},
"TYPE 3": {
"answer": {
"13": "59381701-AFBC-48F8-AECE-DB3702EE2B15",
"14": "7F4AC694-74DC-4BEA-ACFB-D8F070769FEE"
},
"survey": {
"15": "B5C405B9-BA7E-471A-87DD-B69D9757276F"
}
}
}
Fetch that result into your client app. It's a single long string, so I hope your data is not longer than MySQL's max_allowed_packet
length.
Convert the string into your desired nested array with json_decode().
Related Topics
How to Read Any Request Header in PHP
Understanding MVC Views in PHP
The Plugin Generated X Characters of Unexpected Output During Activation (Wordpress)
How to Use Password Hashing With Pdo to Make My Code More Secure
Select Count(*) as Count - How to Use This Count
How to Create Multiple Where Clause Query Using Laravel Eloquent
Unicode Character in PHP String
Is There a PHP Function That Can Escape Regex Patterns Before They Are Applied
Insert New Item in Array on Any Position in PHP
PHP Domdocument Loadhtml Not Encoding Utf-8 Correctly
Converting String to Date and Datetime
Laravel Csrf Token Mismatch For Ajax Post Request
How to Encrypt/Decrypt Data in PHP