php - Create rows of values from original row keys, and column values (transpose subarray keys & columns)
168
I need to restructure some array data then pass it as a json string to generate a Google line chart.
In the result array, I need to create rows of three elements.
- the original element keys which are shared among all rows.
- the values from the first row.
- the values from the second row.
Input array:
[
1 => [
1 => 'c1',
2 => 'c1',
3 => 'c1',
4 => 'c1',
5 => 'c1'
],
10 => [
1 => 'c2',
2 => 'c2',
3 => 'c2',
4 => 'c2',
5 => 'c2'
]
]
Expected result is:
[[1,"c1","c2"],[2,"c1","c2"],[3,"c1","c2"],[4,"c1","c2"],[5,"c1","c2"]]
Answer
Solution:
Two nested loops should do the trick in this case:
This produces an array that looks like the following:
This can the easily be converted to your desired output:
Which will produce:
Answer
Solution:
the below code will produce string as you wanted
output
Answer
Solution:
For output as strings inside array:
output:
Answer
Solution:
Here is an example that will work with any number of arrays:
Since the expected output looks like JSON string i will use json_encode:
Or if you want the string without the quotes:
Answer
Solution:
You merely need to include the keys from the first row in your array transposition.
Also, it is crucial that you never manually generate json string by string concatenation (or any other manual method). The surest way to generate a valid json string is to call
json_encode()
.Code: (Demo)