This question already has answers here:
Transposing multidimensional arrays in PHP
(12 answers)
Closed 6 months ago.
I'm not sure how to search for the problem I'm facing, so that's why I'm asking here.
I want to know if there is a native php-function to transform following array I get from a html-form:
Original Array
$array = [
'product_template_id' => [
'0' => '1',
'1' => '2'
],
'amount' => [
'0' => '50',
'1' => '100'
]
]
Desired Array
$array = [
'0' => [
'product_template_id' => '1',
'amount' => '50'
],
'1' => [
'product_template_id' => '2',
'amount' => '100'
]
]
I know this can be done with a loop, but that's not what I'm asking for.
PS(not my main question, just a sidequestion): How can I bulk format code in stackoverflow? Is it always 4 spaces? How can I perform the formatting quicker?
edit: PS is not the main question, it is more of a sidenote which has already been answered by #RiggsFolly
Just as prove of concept you can use array_map:
$keys = array_keys($array);
// For < PHPv5.6
// $zip = call_user_func_array('array_map', array_merge([null], $array));
$zip = array_map(null, ...array_values($array));
$result = array_map(function ($item) use ($keys) {
return array_combine($keys, $item);
}, $zip);
Here is working demo.
But in practice, there is too much overhead for so simple problem.
EDIT:
Here I am zipping (getting one corresponding element from each array and creating an array of this elements) all child arrays. It is done with array_map using its property:
An interesting use of this function is to construct an array of arrays, which can be easily performed by using NULL as the name of the callback function
As array_map can take an arbitrary number of arrays, I supply them to it with '...' splat operator.
This does what you need!
for ($x = 0; $x < count($array['amount']); $x ++) {
$arr[$x] = [
'product_template_id' => $array['product_template_id'][$x],
'amount' => $array['amount'][$x],
];
}
See here for a working example https://3v4l.org/dokHK
Related
This question already has answers here:
Is there a function to extract a 'column' from an array in PHP?
(15 answers)
Closed 9 months ago.
I have this array. I want to get the array values to a same array,how can I achieve that?
Array
(
[0] => Array
(
[referrer_id] => usr157
)
[1] => Array
(
[referrer_id] => usr42
)
)
I want this array to be
array("usr157", "usr42")
use array_walk_recursive to achieve the result as follows
<?php
$main = [];
$ref =
[
[
"referrer_id" => "usr157"
],
[
"referrer_id" => "usr42"
]
];
array_walk_recursive($ref, function ($item, $key) use(&$main) {
$main[] = $item;
} );
print_r($main);
You can check that out here
You can just access the array components like this:
// The next line just recreates your example array into a variable called $x:
$x = array(array('referrer_id' => 'usr157'), array('referrer_id' => 'usr42'));
$result = array($x[0]['referrer_id'], $x[1]['referrer_id']);
print_r($result); //print the result for correctness checking
$result will be the output array you wanted.
Using $x[0], you refer the first element of your input array (and hence, $x[1] the second one, ...). Adding ['referrer_id'] will access its referrer_id key. The surrounding array(...) puts the values into an own array.
You can "automate" the whole thing in case you have a bigger input array using a loop.
You may use array_column to achieve that
$flatten = array_column($array, 'referrer_id');
You can also use array_map and array_values together.
$array = [
[
"referrer_id" => "usr157"
],
[
"referrer_id" => "usr42"
]
];
$flatten = array_map(function($item) {
return array_values($item)[0];
}, $array);
var_dump($flatten);
Also you can use the one-liner if you're using latest version of php that support arrow function
$flatten = array_map(fn($item) => array_values($item)[0], $array);
Or without array_values, you may specify the key
$flatten = array_map(fn($item) => $item['referrer_id'], $array);
You can see the demo here
This question already has answers here:
Transposing multidimensional arrays in PHP
(12 answers)
Closed 8 months ago.
I'm using the array_column function to convert a 3d array into new arrays with the values.
I have multiple columns that all need to be converted in an array. Is there an easier or cleaner way to do this?
Instead of doing this:
$levels = array_column($arr, 'level');
$times = array_column($arr, 'time');
$numbers = array_column($arr, 'number');
Here's an example of my array:
$arr = [
[
'level' => 0,
'time' => 3,
'number' => 5
],
[
'level' => 1,
'time' => 4,
'number' => 3
],
];
I think the simplest way to do this is with a nested loop.
foreach($arr as $inner) {
foreach($inner as $key => $value) {
$columns[$key][] = $value;
}
}
This will produce a result like this:
[
'level' => [0, 1],
'time' => [3, 4],
'number' => [5, 3]
]
If you really want to create separate variables like the example in your question, you can use variable variables for that. I would advise against it, but here's an example of that.
foreach($arr as $inner) {
foreach($inner as $key => $value) {
$$key[] = $value;
}
}
Dynamically creating variables like that is risky. You can inadvertently overwrite other variables if one of the column names happens to be the same. Using the first method will contain the result in one predictable place, and $columns['level'] can be used in the following code just the same as a separate $level variable would.
This question already has answers here:
Custom key-sort a flat associative based on another array
(16 answers)
Closed 2 years ago.
Quick question, most likely for a veteran will be easy, or maybe im asking for too much.
i have this code for laravel in php, im not fan to do a foreach, is there a better way? i guess should be an existing function that replace my values of arr to the keys match on arr2, but i dont know
Its really important not to change the order.
$arr= ['filters', 'repeat', 'via', 'type'];
$arr2= [
'filters' => 'text1',
'repeat' => 'text2',
'via' => 'text3',
'type' => 'text4',
];
foreach($arr as $k)
$res[]=$arr2[$k];
return $res;
You can do it using array_map.
$arr= ['filters', 'repeat', 'via', 'type'];
$arr2 = [
'filters' => 'text1',
'repeat' => 'text2',
'via' => 'text3',
'type' => 'text4',
];
$res = array_map(function($key) use($arr2) {
return $arr2[$key];
}, $arr);
print_r($res);
You can use Laravel's array_only helper function:
$res = array_only($arr2, $arr);
If you don't want to preserve the keys then you can use the array_values function too:
$res = array_values(array_only($arr2, $arr));
Yes, two ways:
Use array_values(), assuming the values of $arr are exactly in the same order as the keys in $arr2 and always have the same keys. I'm guessing this is not exactly what you meant, but that's what your example shows. If that's the case, then it is as simple as:
$res = array_values($arr2)
Use array_map() to map the values of one array (in this case $arr) to a new array ($res):
$mapper = function($k) use ($arr2) {
return $arr2[$k];
};
$res = array_map($mapper, $arr);
You can then also add handling of cases where $k does not exist in $arr2, e.g. return null and then use array_filter to filter out the null values;
(I did not test this code but generally, this is the approach)
You can use Collection in Laravel
$res = collect($arr)->map(function ($key) use ($arr2) {
return $arr2[$key];
})->toArray()
If you just want the array values you can use the array_values() function.
$arr2= [
'filters' => 'text1',
'repeat' => 'text2',
'via' => 'text3',
'type' => 'text4',
];
$res = array_values($arr2);
This will result in the following array:
['text1', 'text2', 'text3', 'text4']
i have this two arrays:
$array1 = [
'1' => 285.52,
'2' => 427.76
];
$array2 = [
'1' => 123.44,
'2' => 48.32
];
The keys on each of them are the id for the client, the first one is the amount owed and the second one is the amount payed, i want to achieve the following:
$mergedArrays = [
'1' => [
'owed' => 285.52,
'payed' => 123.44
],
'2' => [
'owed' => 427.76,
'payed' => 48.32
]
];
I was wondering if there's a PHP function to do so, i tried with array_merge_recursive but it just makes an array with the four elements together.
Any help would be really appreciated.
you can loop in the first array and merge the second according to keys
foreach($array1 as $key => $val) {
$mergedArrays[$key] = array('owed' => $val, 'payed' => $array2[$key]);
}
sample
$array1 = [
'1' => 285.52,
'2' => 427.76
];
$array2 = [
'1' => 123.44,
'2' => 48.32
];
$final_arr = array_map(function($a1, $a2) {
return array(
'owed' => $a1,
'paid' => $a2
);
}, $array1, $array2);
$final_arr = array_combine(array_keys($array1), $final_arr);
var_dump($final_arr);
Based on the comment, it seems you're looking for built-in PHP functions to do the task for you rather than going for traditional looping. But the looping method provided by Fabio is the simplest one you could go for without any other complicated approaches. I've tried my best to provide you the solution using the core PHP functions. Hope you're happy with it!
This question already has answers here:
Is there a function to extract a 'column' from an array in PHP?
(15 answers)
Closed 6 years ago.
I need to change this array:
$array = [
[0] => [
'id' => '100'
],
[1] => [
'id' => '200'
],
[2] => [
'id' => '300'
]
];
Into this:
$array2 = [100, 200, 300];
A long time ago I found a built-in PHP function which could do this for me. But i can't for the life of me remember which one it was. Of course I could do it manually, but it would be easier and more readable if I could use a builtin PHP function
Use array_column like this: array_column($array, 'id');
1st solution:
Use array_map() function with inline function:
$array2 = array_map(function($arrayElement){return $arrayElement['id'];}, $array);
2nd solution:
Use foreach loop:
function getValues($array, $index)
{
$result = array();
foreach($array as $element)
{
if(isset($element[$index])) //check if index exists
$result[] = $element[$index];
}
return $result;
}
$array2 = getValues($array, 'id');
This function has two parameters: array from which you gets values and index, for example 'id'.
Result of two methods is the same:
Array
(
[0] => 100
[1] => 200
[2] => 300
)