Change recursive array into single array with same key - php

i want to know if it's possible to change an array structure, currently i'm receiving this array:
[{"ano":["2004","2006"]},{"ano":["2006",""]},{"ano":["2011",""]},{"ano":["2013",""]}]
I need those dates split one by row like this:
[{"ano":"2004"},{"ano":"2006"},{"ano":"2006"},{"ano":"2011"}]
So, basically i'm think i could clean empty and duplicated values, and then split the array or something?
I'm using PHP and MySQL SELECT to return those values like this:
while($ano = $pegaAno->fetchObject()){
$ar1 = array("ano" => $ano->inicio);
$ar2 = array("ano" => $ano->fim);
$result = array_merge_recursive($ar1, $ar2);
//print_r($result);
array_push($return_arr,$result);
}
Any help please?

while($ano = $pegaAno->fetchObject())
array_push($return_arr, array("ano" => $ano->inicio), array("ano" => $ano->fim));
$return_arr = array_unique($return_arr);
Perhaps you want something like this? So you can have an array as
0 => [ "ano" => value ]
1 => [ "ano" => value ]
2 => [ "ano" => value ]
//etc...

You may also try this code
$input[0]['anno'] = array("2004","2006");
$input[1]['anno'] = array("2008","");
$input[2]['anno'] = array("2002","2006");
$input[3]['anno'] = array("2004","2013");
$arr = array();
foreach ($input as $value) {
foreach ($value as $key => $value1) {
foreach ($value1 as $value2) {
$arr[] = $value2;
}
}
}
$resulted = array_filter(array_unique($arr));
$resulted_array = array();
foreach ($resulted as $value) {
$resulted_array[][$mainkey] = $value;
}
print_r($resulted_array);
//RESULT
Array
(
[0] => Array
(
[anno] => 2004
)
[1] => Array
(
[anno] => 2006
)
[2] => Array
(
[anno] => 2008
)
[3] => Array
(
[anno] => 2002
)
[4] => Array
(
[anno] => 2013
)
)

Related

php merge arrays and change its grouping [duplicate]

I have a multidimensional array and am trying to group them according to the value in a specific column.
I'm trying to group them by level, but I won't actually know the level beforehand. So, it's not like I can put it in a for loop and say while $i < 7, because I won't know that 7 is the maximum value for the level key, and frankly, I'm not sure that's how I would need to do it even if I did.
[
['cust' => 'XT8900', 'type' => 'standard', 'level' => 1],
['cust' => 'XT8944', 'type' => 'standard', 'level' => 1],
['cust' => 'XT8922', 'type' => 'premier', 'level' => 3],
['cust' => 'XT8816', 'type' => 'permier', 'level' => 3],
['cust' => 'XT7434', 'type' => 'standard', 'level' => 7],
]
Desired result:
Array (
[1] => Array (
[0] => Array (
[cust] => XT8900
[type] => standard
)
[1] => Array (
[cust] => XT8944
[type] => standard
)
)
[3] => Array (
[2] => Array (
[cust] => XT8922
[type] => premier
)
[3] => Array (
[cust] => XT8816
[type] => permier
)
)
[7] => Array (
[4] => Array (
[cust] => XT7434
[type] => standard
)
)
)
Best way, if you have control over building the initial array, is just set things up like that at the start as you add entries.
If not then build a temporary array to sort:
foreach ($input_arr as $key => &$entry) {
$level_arr[$entry['level']][$key] = $entry;
}
Leaves you with the form you wanted and everything referenced together.
Build the array like that in the first place though if at all possible.
You need to group them by level first
Use foreach to loop into array check if the level is the same with the previous item then group it with that array
$templevel=0;
$newkey=0;
$grouparr[$templevel]="";
foreach ($items as $key => $val) {
if ($templevel==$val['level']){
$grouparr[$templevel][$newkey]=$val;
} else {
$grouparr[$val['level']][$newkey]=$val;
}
$newkey++;
}
print($grouparr);
The output of print($grouparr); will display like the format you hoped for
You can also try to
print($grouparr[7]);
Will display
[7] => Array (
[4] => Array (
[cust] => XT7434
[type] => standard
)
)
Or
print($grouparr[3]);
Will display
[3] => Array (
[2] => Array (
[cust] => XT8922
[type] => premier
)
[3] => Array (
[cust] => XT8816
[type] => permier
)
)
Here is the solution I landed on for an identical problem, wrapped as a function:
function arraySort($input,$sortkey){
foreach ($input as $key=>$val) $output[$val[$sortkey]][]=$val;
return $output;
}
To sort $myarray by the key named "level" just do this:
$myArray = arraySort($myArray,'level');
Or if you didn't want it as a function, just for a one time use, this would create $myNewArray from $myArray grouped by the key 'level'
foreach ($myArray as $key=>$val) $myNewArray[$val['level']][]=$val;
function group_assoc($array, $key) {
$return = array();
foreach($array as $v) {
$return[$v[$key]][] = $v;
}
return $return;
}
//Group the requests by their account_id
$account_requests = group_assoc($requests, 'account_id');
$result = array();
foreach ($yourArrayList as $data) {
$id = $data['level'];
if (isset($result[$id])) {
$result[$id][] = $data;
} else {
$result[$id] = array($data);
}
}
Best ans.
$levels = array_unique(array_column($records, 'level'));
$data = array();
foreach($records as $key => $value){
$data[$levels[array_search($value['level'],$levels )]][] = $value ;
}
print_r($data);
To generate the question's exact desured output from the sample input, pull/pop the last value from each row, use that value as the first level grouping key. Then use the original first level index as the second level key. Then push the two remaining elements into the group's subset.
Code: (Demo)
$result = [];
foreach ($array as $key => $row) {
$result[array_pop($row)][$key] = $row;
}
var_export($result);
For functional style syntax, use array_reduce(). (Demo)
var_export(
array_reduce(
array_keys($array),
function($result, $key) use ($array) {
$result[array_pop($array[$key])][$key] = $array[$key];
return $result;
}
)
);
function _group_by($array,$key,$keyName)
{
$return = array();
foreach($array as $val) {
$return[$keyName.$val[$key]][] = $val;
}
return $return;
} //end of function

How can I extract values from an array (array_values isn't working)?

I have the following PHP array
[1] => Array
(
[0] => 9780881220766
[1] => 0881220760
)
[2] => Array
(
[0] => 9780141374284
[1] => 0141374284
)
[3] => Array
(
[0] => 057305133X
[1] => 9780573051333
))
I would like the output to be as follows:
[0] => 9780881220766
[1] => 0881220760
[2] => 9780141374284
[3] => 0141374284
[4] => 057305133X
[5] => 9780573051333
I tried using array_values but I'm not getting any output.
I also tried to extract the values using a foreach loop:
foreach ($rawIsbns as $isbnKey => $isbnValue){
$formattedIsbns[] = $isbnValue;
}
However, I'm not managing.
$a = array();
foreach ($array as $tmp) {
if (is_array($tmp)) $a = array_merge($a, $tmp);
}
Created this function that allows you to merge 1 or more arrays together into the format you asked for:
function sortarr(...$arr){
$tmparr = [];
foreach($arr as $aa) foreach($aa as $a) $tmparr = array_merge($tmparr, $a);
return $tmparr;
}
Example Usage:
<?php
# First array provided
$array = array(
[
"9780881220766",
"0881220760"
],
[
"9780141374284",
"0141374284"
],
[
"057305133X",
"9780573051333"
]
);
# Second array just to show how you can input more than 1 array into the function
$array2 = array(
[
"6234808972234",
"67834757"
],
[
"0287568924344234",
"234690543"
],
[
"34565786978099x",
"3569876546"
]
);
function sortarr(...$arr){
# Declare our temp array
$tmparr = [];
# Iterates through each of the arrays inside the array(s) provided
foreach($arr as $aa) foreach($aa as $a) $tmparr = array_merge($tmparr, $a);
# Return the results
return $tmparr;
}
print_r( sortarr($array, $array2) );
Results:
Array
(
[0] => 9780881220766
[1] => 0881220760
[2] => 9780141374284
[3] => 0141374284
[4] => 057305133X
[5] => 9780573051333
[6] => 6234808972234
[7] => 67834757
[8] => 0287568924344234
[9] => 234690543
[10] => 34565786978099X
[11] => 3569876546
)
Live Demo: http://sandbox.onlinephpfunctions.com/code/838a108498f446ae4a5f8e42fa441ec11941c567
I managed to solve the problem by initializing an array and adding values of subsequent nested arrays using array_push
function isbns($rawIsbns) {
$prevArrayValues = null;
foreach ($rawIsbns as $value) {
if (!isset($prevArrayValues)) {
$prevArrayValues = []; //initiallise first value unless initialized
}
if (empty($value)) {
$return = []; //disregard empty values
} else {
$return = $value; // add arrays to existing array
}
$prevArrayValues = array_merge($prevArrayValues, $return);
}
return $prevArrayValues;
}

codeigniter modify array from string for insert_batch

This is my form input $data, i want this keep this input.
$data = "39X3,29X5";
this my code convert string to array
$data = explode(",", $data);
$out = array();
$step = 0;
foreach($data as $key=>$item){
foreach(explode('X',$item) as $value){
$out[$key][$step++] = $value;
}
print '<pre>';
print_r($out);
print '</pre>';
result
Array
(
[0] => Array
(
[0] => 39
[1] => 3
)
[1] => Array
(
[2] => 29
[3] => 5
)
)
but i want change the keys and fix this for support query builder class
$this->db->insert_batch('mytable',$out).
Like this.
array
(
array
(
'number' => 39
'prize' => 3
),
array
(
'number' => 29
'prize' => 5
)
)
i try hard and confuse using loop.
So you need to remove inner foreach and put relevant values into array.
foreach($data as $key=>$item){
$exp = explode('X', $item);
$out[$key] = [
'number' => $exp[0],
'prize' => $exp[1]
];
}
Check result in demo
change your foreach loop to the following:
foreach($data as $key=>$item){
$temp = explode('X',$item);
$out[] = ['number' => $temp[0] , 'prize' => $temp[1]];
}

Adding same element to every level of array php

I need to add another another element to each level of the array (sorry, think that is bad terminology).
I have an array -
Array ( [0] => Array (
[actor_rt_id] => 162683283,
[item_number] => 3 )
[1] => Array (
[actor_rt_id] => 162657351,
[item_number] => 5 )
)
This code produces the array. The commented out line is what I tried to add to the array. The code before the comment creates the array.
$data_itemone['actor_rt_id'] = $this->input->post('actor_id');
$data_itemtwo['item_number'] = $this->input->post('item_number');
$data_item = array_merge($data_itemone, $data_itemtwo);
$res = [];
foreach($data_item as $key => $value){
foreach ($value as $data => $thevalue) {
$res[$data][$key] = $thevalue;
//$res['film_id'] = $film_id;
}
}
I have an another variable I need to add from post which is a single string.
$film_id = $this->input->post('film_id');
I need it to be in the array like so -
Array ( [0] => Array (
[actor_rt_id] => 162683283,
[item_number] => 3,
[film_id] => 52352
)
[1] => Array (
[actor_rt_id] => 162657351,
[item_number] => 5,
[film_id] => 52352
)
)
...but my code (uncommented) produces -
Array ( [0] => Array (
[actor_rt_id] => 162683283,
[item_number] => 3
)
[film_id] => 16639,
[1] => Array
( [actor_rt_id] => 162657351,
[item_number] => 5 )
)
Tried a few things. Can't seem to get it to work.
Change
$res['film_id'] = $film_id;
to
$res[$data]['film_id'] = $film_id;
this will add it to the right array.
How if you try this.
$data_itemone['actor_rt_id'] = [123, 245];
$data_itemtwo['item_number'] = [456, 789];
$film_id = 52352;
$data_item = array_merge($data_itemone, $data_itemtwo);
$res = [];
foreach($data_item as $key => $value){
foreach ($value as $data => $thevalue) {
$res[$data][$key] = $thevalue;
$res[$data]['film_id'] = $film_id;
}
}
print_r($res);
Try this one
<?
$data_itemone['actor_rt_id'] = $this->input->post('actor_id');
$data_itemtwo['item_number'] = $this->input->post('item_number');
$film_id = $this->input->post('film_id');
$data_item = array_merge($data_itemone, $data_itemtwo);
$res = [];
foreach($data_item as $key => $value){
foreach ($value as $data => $thevalue) {
$res[$data][$key] = $thevalue;
$res[$data]['film_id'] = $film_id;
}
}
?>

Group 2d array data using column value to create a 3d array

I have a multidimensional array and am trying to group them according to the value in a specific column.
I'm trying to group them by level, but I won't actually know the level beforehand. So, it's not like I can put it in a for loop and say while $i < 7, because I won't know that 7 is the maximum value for the level key, and frankly, I'm not sure that's how I would need to do it even if I did.
[
['cust' => 'XT8900', 'type' => 'standard', 'level' => 1],
['cust' => 'XT8944', 'type' => 'standard', 'level' => 1],
['cust' => 'XT8922', 'type' => 'premier', 'level' => 3],
['cust' => 'XT8816', 'type' => 'permier', 'level' => 3],
['cust' => 'XT7434', 'type' => 'standard', 'level' => 7],
]
Desired result:
Array (
[1] => Array (
[0] => Array (
[cust] => XT8900
[type] => standard
)
[1] => Array (
[cust] => XT8944
[type] => standard
)
)
[3] => Array (
[2] => Array (
[cust] => XT8922
[type] => premier
)
[3] => Array (
[cust] => XT8816
[type] => permier
)
)
[7] => Array (
[4] => Array (
[cust] => XT7434
[type] => standard
)
)
)
Best way, if you have control over building the initial array, is just set things up like that at the start as you add entries.
If not then build a temporary array to sort:
foreach ($input_arr as $key => &$entry) {
$level_arr[$entry['level']][$key] = $entry;
}
Leaves you with the form you wanted and everything referenced together.
Build the array like that in the first place though if at all possible.
You need to group them by level first
Use foreach to loop into array check if the level is the same with the previous item then group it with that array
$templevel=0;
$newkey=0;
$grouparr[$templevel]="";
foreach ($items as $key => $val) {
if ($templevel==$val['level']){
$grouparr[$templevel][$newkey]=$val;
} else {
$grouparr[$val['level']][$newkey]=$val;
}
$newkey++;
}
print($grouparr);
The output of print($grouparr); will display like the format you hoped for
You can also try to
print($grouparr[7]);
Will display
[7] => Array (
[4] => Array (
[cust] => XT7434
[type] => standard
)
)
Or
print($grouparr[3]);
Will display
[3] => Array (
[2] => Array (
[cust] => XT8922
[type] => premier
)
[3] => Array (
[cust] => XT8816
[type] => permier
)
)
Here is the solution I landed on for an identical problem, wrapped as a function:
function arraySort($input,$sortkey){
foreach ($input as $key=>$val) $output[$val[$sortkey]][]=$val;
return $output;
}
To sort $myarray by the key named "level" just do this:
$myArray = arraySort($myArray,'level');
Or if you didn't want it as a function, just for a one time use, this would create $myNewArray from $myArray grouped by the key 'level'
foreach ($myArray as $key=>$val) $myNewArray[$val['level']][]=$val;
function group_assoc($array, $key) {
$return = array();
foreach($array as $v) {
$return[$v[$key]][] = $v;
}
return $return;
}
//Group the requests by their account_id
$account_requests = group_assoc($requests, 'account_id');
$result = array();
foreach ($yourArrayList as $data) {
$id = $data['level'];
if (isset($result[$id])) {
$result[$id][] = $data;
} else {
$result[$id] = array($data);
}
}
Best ans.
$levels = array_unique(array_column($records, 'level'));
$data = array();
foreach($records as $key => $value){
$data[$levels[array_search($value['level'],$levels )]][] = $value ;
}
print_r($data);
To generate the question's exact desured output from the sample input, pull/pop the last value from each row, use that value as the first level grouping key. Then use the original first level index as the second level key. Then push the two remaining elements into the group's subset.
Code: (Demo)
$result = [];
foreach ($array as $key => $row) {
$result[array_pop($row)][$key] = $row;
}
var_export($result);
For functional style syntax, use array_reduce(). (Demo)
var_export(
array_reduce(
array_keys($array),
function($result, $key) use ($array) {
$result[array_pop($array[$key])][$key] = $array[$key];
return $result;
}
)
);
function _group_by($array,$key,$keyName)
{
$return = array();
foreach($array as $val) {
$return[$keyName.$val[$key]][] = $val;
}
return $return;
} //end of function

Categories