I have array like this:
$arr = [];
$arr['cat1']=[
'attributes'=>[
[
'attributeName'=>'name1',
'attrSortOrder'=>'1'
],
[
'attributeName'=>'name2',
'attrSortOrder'=>'5'
],
[
'attributeName'=>'name3',
'attrSortOrder'=>'2'
],
],
'category_id'=>10
];
$arr['cat2']=[
'attributes'=>[
[
'attributeName'=>'name4',
'attrSortOrder'=>'5'
],
[
'attributeName'=>'name5',
'attrSortOrder'=>'7'
],
[
'attributeName'=>'name6',
'attrSortOrder'=>'2'
],
],
'category_id'=>12
];
I need for each $arr element sort 'attributes' by attrSortOrder column.
I tried it:
function array_sort_by_column(&$arr, $col, $dir = SORT_ASC) {
$sort_col = array();
foreach ($arr as $key=> $row) {
$sort_col[$key] = strtolower($row[$col]);
}
array_multisort($sort_col, $dir, $arr);
}
array_sort_by_column($arr,'attrSortOrder');
But it did not help me. How can solve this? How can i sort my array correctly?
Thanks.
Change your function to
function array_sort_by_column(&$arr, $col, $dir = SORT_DESC) {
foreach($arr as &$v){//pass by reference each sub-array
array_multisort(array_column($v['attributes'], 'attrSortOrder'), $dir, $v['attributes']);
}
}
array_sort_by_column($arr,'attrSortOrder');
You can change second argument SORT_DESC OR SORT_ASC
Working example :- https://3v4l.org/pQ0Eu
Related
I want to combine two different multi-dimensional arrays, with one providing the correct structure (keys) and the other one the data to fill it (values).
Notice that I can't control how the arrays are formed, the structure might vary in different situations.
$structure = [
"a",
"b" => [
"b1",
"b2" => [
"b21",
"b22"
]
]
];
$data = [A, B1, B21, B22];
Expected result:
$array = [
"a" => "A",
"b" => [
"b1" => "B1",
"b2" => [
"b21" => "B21",
"b22" => "B22"
]
]
];
You can use the following code, however it will only work if number of elements in $data is same or more than $structure.
$filled = 0;
array_walk_recursive ($structure, function (&$val) use (&$filled, $data) {
$val = array( $val => $data[ $filled ] );
$filled++;
});
print_r( $structure );
Here is a working demo
You can try by a recursive way. Write a recursive method which takes an array as first argument to alter and the data set as its second argument. This method itself call when any array element is another array, else it alters the key and value with the help of data set.
$structure = [
"a",
"b" => [
"b1",
"b2" => [
"b21",
"b22"
]
]
];
$data = ['A', 'B1', 'B21', 'B22'];
function alterKey(&$arr, $data) {
foreach ($arr as $key => $val) {
if (!is_array($val)) {
$data_key = array_search(strtoupper($val), $data);
$arr[$val] = $data[$data_key];
unset($arr[$key]);
} else {
$arr[$key] = alterKey($val, $data);
}
}
ksort($arr);
return $arr;
}
alterKey($structure, $data);
echo '<pre>', print_r($structure);
Working demo.
This should work.
$structure = [
"a",
"b" => [
"b1",
"b2" => [
"b21",
"b22"
]
]
];
$new_structure = array();
foreach($structure as $key =>$value)
{
if(!is_array($value))
{
$new_structure[$value]= $value;
}else{
foreach($value as $k =>$v)
{
if(!is_array($v))
{
$new_structure[$key][$v]=$v;
}else
{
foreach($v as $kk => $vv)
{
$new_structure[$k][$vv]=$vv;
}
}
}
}
}
print_r($new_structure);exit;
Use
$array=array_merge($structure,$data);
for more information follow this link
how to join two multidimensional arrays in php
I have problem with convert array. I have structure like as
$threeDimensionalArray = [
[
[
'name' => 'name1',
],
[
'name' => 'name2',
],
],
[
[
'time' => 123,
'anyField'=>22222,
'anyField1'=>22222,
'anyField2'=>22222
],
[
'time' => 457,
'anyField'=>22222,
'anyField1'=>22222,
'anyField2'=>22222
],
],
];
I need convert this array to two dimensional and save each array to csv file via fputscsv
example
first line in CSV
'name1','name2',
second line
123, 457, etc
This solution will help in your specific case:
$to_csv = [];
foreach ($threeDimensionalArray as $first_level) {
foreach ($first_level as $second_level) {
foreach ($second_level as $key => $value) {
$to_csv[$key][] = $value;
}
}
}
$fp = fopen('file.csv', 'w');
foreach ($to_csv as $fields) {
fputcsv($fp, $fields);
}
fclose($fp);
The idea is to firstly configure array to two layers array with grouping by key and use fputcsv() afterwards.
I resolve this problem :)
foreach ($threeDimensionalArray as $firstDimensional) {
$array= [];
foreach ($firstDimensional as $twoDimensional) {
$array[] = $twoDimensional['name'] ?? null .$twoDimensional['time'] ?? null;
}
fputcsv($fp, $array);
$returnArray[]=$array;
}
I have an issue with an API I'm developing that returns arrays of lat/lon coordinates. In order to not break the parser on the App side, I need the data to return as uniform nested arrays, like this:
{
coordinates: [
[
-88.451,
41.41
],
[
-85.123,
40.10
],
[
-59.451,
42.42
],
[
-89.124,
44.10
]
]
}
But for some reason the data I'm pulling from is occasionally nested into groups like this:
{
coordinates: [
[
-88.451,
41.41
],
[
-85.123,
40.10
],
[
[
-59.451,
42.42
],
[
-89.124,
44.10
]
],
]
}
If you have a good way to merge these nested arrays into a uniform set of nested arrays [[lat,lon],[lat,lon]] I'd be eternally grateful.
Much thanks,
Rob
$myarray = [
[
-88.451,
41.41
],
[
-85.123,
40.10
],
[
-59.451,
42.42
],
[
-89.124,
44.10
]
];
function contains_array($array) {
foreach ($array as $val) {
if (is_array($val)) {
return true;
}
}
return false;
}
function array_flatten($array, $return) {
foreach ($array as $key => $value) {
if (is_array($value) && contains_array($value)) {
$return = array_flatten($value, $return);
} else {
$return[$key] = $value;
}
}
return $return;
}
$res = array_flatten($myarray, array());
var_dump($res);
This should do the trick
I have a really basic problem. I want to iterate through a multidimensional-array. Suppose I want to add an if statement to check values without breaking the foreach loop... my purpose is to get an array of specific values
$foo = [
'one'=> [
'id'=>1,
'name'=>'32dsfd23'
],
'two' => [
'id'=>1,
'name'=>'322e3'
],
];
function new_func($arr){
$data=[];
foreach($arr as $val) {
foreach($val as $key =>$foofoo) {
if(array_key_exists('id',$val)){
$data['new_arr']=$foofoo;
}
}
}
return $data;
}
echo "<pre>";
print_r(new_func($foo));
echo "</pre>";
The result is :
Array
(
[new_arr] => 322e3
)
And I want to get something like this :
Array
(
[new_arr]
[0]=> 32dsfd23,
[1]=> 322e3,
)
You need to push the new elements in the array. Now you overwrite them.
$foo = [
'one'=> [
'id'=>1,
'name'=>'32dsfd23'
],
'two' => [
'id'=>1,
'name'=>'322e3'
],
];
function new_func($arr){
$data=[];
foreach($arr as $val) {
foreach($val as $key =>$foofoo) {
if(array_key_exists('id',$val)) {
$data['new_arr'][] = $foofoo;
}
}
}
return $data;
}
echo "<pre>";
print_r(new_func($foo));
echo "</pre>";
When you do
$data['new_arr']=$foofoo;
you're overwriting the value in your $data['new_arr'].
You need to change that to $data['new_arr'][]=$foofoo; which will insert the value in that array.
i had a array to each its item was object , i've converted that array with following code :
json_decode(json_encode($array), true)
that the result of code was a array like this :
[
'1'=>[
'slug'=>'a'
'title'=>'foo'
],
'2'=>[
'slug'=>'b'
'title'=>'bar'
],
'3'=>[
'slug'=>'c'
'title'=>'foo'
],
]
now i want to covert this array to somethings like this
[
'a'=>'foom',
'b'=>'bar',
'c'=>'foo',
]
how can i do it ??
Use foreach and array_combine()
foreach ($your_array as $key => $value) {
// get all the keys in $slug array
$slug[] = $value['slug'];
// get all the values in $title array
$title[] = $value['title'];
}
// finally combine and get your required array
$required_array = array_combine($slug, $title);
I think it can also be acheived with -
$requiredArray = array_combine(
array_column($your_array, 'slug'),
array_column($your_array, 'title')
);
You have to iterate over the initial array and create the new one like this:
$array = [
'1'=>[
'slug'=>'a'
'title'=>'foo'
],
'2'=>[
'slug'=>'b'
'title'=>'bar'
],
'3'=>[
'slug'=>'c'
'title'=>'foo'
],
];
$result = [];
foreach($array as $elem){
$index = $elem["slug"];
$value= $elem["title"];
$result[$index] = $value;
}
foreach($array as $elem){
$result[$elem["slug"]] = $elem["title"];
}