Convert threeDimensionalArray to Two and save csv - 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;
}

Related

How to form Json array from sql pdo data in php?

The code that I have does not display what I need, tell me what I'm doing wrong
$new_array =[];
foreach($result as $row)
{
$array =[
'id'=> $row["id"],
'summ' => $row["summ"],
];
foreach($array AS $key => $val) {
$new_array[] = $val;
}
}
echo json_encode($new_array);
Outputs the following result
["26","180","25","35","24","50","23","50","22","100"]
But I need the result to be different, and I can't.
Here's an example of how it should be:
[
{"26","180"},
{"25","35"},
{"24","50"},
{"23","50"},
{"22","100"}
]
Please tell me how to achieve this?
check this :
foreach($result as $row)
$array[] = ['id'=>$row["id"], 'summ'=>$row["summ"]];
echo json_encode($array);
for example if your $result contains such a array :
$result = [['id'=>1, 'summ'=>2] , ['id'=>3, 'summ'=>4] , ['id'=>5, 'summ'=>6]];
the scripts output will be :
[
{"id":1,"summ":2},
{"id":3,"summ":4},
{"id":5,"summ":6}
]
You can skip the inner loop:
$new_array = [];
foreach($result as $row)
{
$new_array[] = [
$row['id'],
$row['summ']
];
}
echo json_encode($new_array);
That should give you the result:
[
["26","180"],
["25","35"],
...
]
Beside other answer,
I usually use array_map for this kind of array transformation.
$result = [['id' => 1, 'summ' => 2], ['id' => 3, 'summ' => 4], ['id' => 5, 'summ' => 6]];
$output = array_map(function ($item) {
return [$item['id'], $item['summ']];
}, $result);

php sort multidimensional array by key

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

How to combine two different multi dimensional arrays (PHP)

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

create multidimensional json array from a json in php

I have a json data. Now I want to reform it. In my json data there is a property like person_on_zone I want to make a property named person_info and store them which person under this area.
Here is my data any code. Thanks in advance
My json data
$val = [
{
'city':'xx',
'zone':'yy',
'person_on_zone':'p1'
},
{
'city':'xx',
'zone':'yy',
'person_on_zone':'p2'
},
{
'city':'xx',
'zone':'yy',
'person_on_zone':'p3'
},
{
'city':'xx',
'zone':'ww',
'person_on_zone':'p1'
},
]
My expectation is
[
{
'city':'xx',
'zone':'yy',
'person_info':{
'person_on_zone':'p1',
'person_on_zone':'p2',
'person_on_zone':'p3',
}
},
{
'city':'xx',
'zone':'ww',
'person_info':{
'person_on_zone':'p1'
}
},
]
Here I tried
foreach ($val as $v) {
$new_array['city'] = $v['city'];
$new_array['zone'] = $v['zone'];
foreach ($val as $v2) {
$new_array['person_info'] = $v['person_on_zone'];
}
}
json_encode($new_array);
Try this, use $map to store key city-zone, then transform to array to get the result
<?php
$val = [
[
'city' => 'xx',
'zone' => 'yy',
'person_on_zone' => 'p1'
],
[
'city' => 'xx',
'zone' => 'yy',
'person_on_zone' => 'p2'
],
[
'city' => 'xx',
'zone' => 'yy',
'person_on_zone' => 'p3'
],
[
'city' => 'xx',
'zone' => 'ww',
'person_on_zone' => 'p1'
]
];
$map = [];
foreach ($val as $v) {
$key = $v['city'] . $v['zone'];
if (!isset($map[$key])) {
$map[$key] = [
'city' => $v['city'],
'zone' => $v['zone'],
'person_info' => []
];
}
$map[$key]['person_info'][] = $v['person_on_zone'];
}
print_r(array_values($map));
Correct Code
foreach ($val as $v){
$new_array['city'] = $v['city'];
$new_array['zone'] = $v['zone'];
foreach ($val as $v2){
$new_array['person_info'] = $v2['person_on_zone'];
}
}
json_encode($new_array);
try this:
first decode json array then use foreach loop with key
$val = json_decode($val);
foreach ($val as $v){
$new_array['city'] = $v->city;
$new_array['zone'] = $v->zone;
foreach ($val as $key=>$v2){
$new_array[$key]['person_info'] = $v->person_on_zone;
}
}
print_r($new_array);
I think you make a mistake around composing the json. I tried with your code and i found following is the correct way to do.. Remember single quote(') is not valid in json string that is being used to define key value pair in php
// I think your code has json string and i convert it into array of objects(stdClass)
// and if your code has array then keep you code intact but need to change the notation of
// objects to associative array.
// first thing first decode json string
$values = json_decode('[
{ "city":"xx",
"zone":"yy",
"person_on_zone":"p1"
},
{
"city":"xx",
"zone":"yy",
"person_on_zone":"p2"
},
{
"city":"xx",
"zone":"yy",
"person_on_zone":"p3"
},
{
"city":"xx",
"zone":"ww",
"person_on_zone":"p1"
}]');
// Now declare new values as array
$new_values = [];
// walk through each object
foreach ($values as $v){
// $v becomes an object of stdClass here
// $data is a temporary array
$data['city'] = $v->city;
$data['zone'] = $v->zone;
$data['person_info'] = [];
foreach ($values as $v2){
if(!in_array($data['person_info'],['person_on_zone' => $v2->person_on_zone]))
{
// compare if zones are same or not
if($v->zone == $v2->zone)
{
// push to the array instead of assiging
array_push($data['person_info'], ['person_on_zone' => $v2->person_on_zone]);
}
}
}
// make array unique
$data['person_info'] = array_map("unserialize", array_unique(array_map("serialize", $data['person_info'])));
array_push($new_values, $data);
}
// make array unique in mutidimensional array
$new_values = array_map("unserialize", array_unique(array_map("serialize", $new_values)));
echo '<pre>';
print_r($new_values);
echo '</pre>';
One simple foreach would do,
$result = [];
foreach ($arr as $key => $value) {
//created unique combination of city and zone as key
$result[$value['city'] . $value['zone']]['city'] = $value['city'];
$result[$value['city'] . $value['zone']]['zone'] = $value['zone'];
$result[$value['city'] . $value['zone']]['person_info'][] = ['person_on_zone' => $value['person_on_zone']];
}
echo json_encode(array_values($result));die;
array_values — Return all the values of an array
Working demo.

Simple foreach loop iteration

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.

Categories