Using PHP to transform a 3D array into a 2D one - php

My form produces a 3 dimensional array. I would like to transform this array into a 2 dimensional one.
I tried this with no success:
$_rows = array();
foreach ($_contacts as $name => $_arr) {
foreach ($_arr as $key => $val) {
$_rows[] = array ($name => $val);
}
}
Data Source:
[_contacts] => Array
(
[name] => Array
(
[0] => foo
[1] => bar
)
[phone] => Array
(
[0] => 012345
[1] => 098765
)
[email] => Array
(
[0] => mail.com
[1] => yahoo.com
)
)
Desired output:
Array
(
[0] => Array
(
[name] => foo
[phone] => 012345
[email] => mail.com
)
[1] => Array
(
[name] => bar
[phone] => 098765
[email] => yahoo.com
)
)
Any thoughts were I went wrong?

$_rows = array();
foreach ($_contacts as $name => $_arr) {
foreach ($_arr as $key => $val) {
$_rows[$key][$name] = $val;
}
}

Related

Convert Multi dimensional array to Single array in PHP

Request your help on how to convert the below array as a single array, I tried all these methods:
array_column($testarray, "Name") ,
array_merge($array, , $testarray),
array_map('current', $$testarray[0])
but nothing seem to be working. Basically I need to passes the array value as a string using implode("','", Name) so that the array value would be like below
T : 'Name1','Name2'
D : 'Name11','Name21'
P : 'Name111','Name211'
Original Array
Array
(
[T] => Array
(
[0] => Array
(
[Name] => Name1
)
[1] => Array
(
[Name] => Name2
)
)
[D] => Array
(
[0] => Array
(
[Name] => Name11
)
[1] => Array
(
[Name] => Name21
)
)
[P] => Array
(
[0] => Array
(
[Name] => Name111
)
[1] => Array
(
[Name] => Name211
)
)
)
Expected Array
T:
Name: Name1
Name2
D:
Name: Name11
Name21
P:
Name: Name111
Name211
From,
Vino
try this one
function array_flatten($array) {
if (!is_array($array)) {
return FALSE;
}
$result = array();
foreach ($array as $key => $value) {
if (is_array($value)) {
$result = array_merge($result, array_flatten($value));
}
else {
$result[$key] = $value;
}
}
return $result;
}
You can flatten your array using array_map and array_column:
$newarr = array_map(function ($v) { return array_column($v, 'Name'); }, $array);
print_r($newarr);
This gives:
Array
(
[T] => Array
(
[0] => Name1
[1] => Name2
)
[D] => Array
(
[0] => Name11
[1] => Name21
)
[P] => Array
(
[0] => Name111
[1] => Name211
)
)
You can then output the key with each array imploded for your string result:
foreach ($newarr as $key => $arr) {
echo "$key: " . implode(',', $arr) . "\n";
}
Output:
T: Name1,Name2
D: Name11,Name21
P: Name111,Name211
Demo on 3v4l.org
$arr = [
'T' => [['Name' => 'Name1'], ['Name' => 'Name2']],
'D' => [['Name' => 'Name11'], ['Name' => 'Name11']],
'P' => [['Name' => 'Name111'], ['Name' => 'Name211']]
];
array_walk($arr,function(&$v, $k){
$v = ['Name' => array_column($v, 'Name')];
});
print_r($arr);
OUTPUT:
Array
(
[T] => Array
(
[Name] => Array
(
[0] => Name1
[1] => Name2
)
)
[D] => Array
(
[Name] => Array
(
[0] => Name11
[1] => Name11
)
)
[P] => Array
(
[Name] => Array
(
[0] => Name111
[1] => Name211
)
)
)

How to move Array up another level by key

I have an array like below and what I want to achieve is basically remove the keys like #attributes and AddressSop and make them all one level so it removes the parent keys and array but keeps the key value pairs:
[Addresses] => Array
(
[0] => Array
(
[AddrCountry] => US
[AddrLine1] => Test Street
[AddrLine2] => Test
[AddrLine3] => Test
[AddrName] => Mr John Doe
[AddrEmail] => test#test.com
[AddrMasterPriceBook] =>
[AddrMobile] => 123132142242
)
[1] => Array
(
...
)
)
This is how the original array looks. Any help will be awesome thank you.
[Addresses] => Array
(
[0] => Array
(
[#attributes] => Array
(
[AddrCountry] => US
[AddrLine1] => Test Street
[AddrLine2] => Test
[AddrLine3] => Test
[AddrName] => Mr John Doe
)
[AddressSOP] => Array
(
[#attributes] => Array
(
[AddrEmail] => test#test.com
[AddrMasterPriceBook] =>
[AddrMobile] => 123132142242
)
)
)
[1] => Array
(
[#attributes] => Array
(
[AddrCountry] => US
[AddrLine1] => Test Street
[AddrLine2] => Test
[AddrLine3] => Test
[AddrName] => Mr John Doe
)
[AddressSOP] => Array
(
[#attributes] => Array
(
[AddrEmail] => test#test.com
[AddrMasterPriceBook] =>
[AddrMobile] => 123132142242
)
)
)
)
Try this:
foreach ($addresses as $key => $address) {
$addresses[$key] = array_merge($address['#attributes'], $address['AddressSOP']);
}
If you want it to be recursive, you can do something like this:
$filtered = [];
foreach ($addresses as $addressKey => $address) {
array_walk_recursive($address, function($val, $key) use(&$filtered, $addressKey) {
$filtered[$addressKey][$key] = $val;
});
}
print_r($filtered);

Bulid for loop based on given array

I am generating dynamic textbox for save and add more functionality and i have to store that data in database i got the array but i dont know how to put that array in to loop so i can get my data.
Array looks like this based on this prepare loop so i can access every element of array:
Array
(
[0] => Array
(
[0] => Array
(
[0] => Array
(
[prem_type] => 1
)
[1] => Array
(
[phase_name] => a1
)
[2] => Array
(
[counter] => 2
)
[3] => Array
(
[block] => A
)
[4] => Array
(
[block] => B
)
)
)
[1] => Array
(
[0] => Array
(
[0] => Array
(
[prem_type] => 1
)
[1] => Array
(
[phase_name] => a2
)
[2] => Array
(
[counter] => 2
)
[3] => Array
(
[block] => A
)
[4] => Array
(
[block] => B
)
)
)
)
Thanks
try this
$array = //your array
foreach($array as $value){
foreach($value as $value2){
foreach($value2 as $value3){
foreach($value3 as $key3 => $value3){
//$key3 is rem_type, phase_nameā€¦
//$value3 is required values
}
}
}
}
To get to the data you can use something like:
foreach ($array AS $row) {
$prem_type = $row[0][0]['prem_type'];
$phase_name = $row[0][1]['phase_name'];
$counter = $row[0][2]['counter'];
$block1 = $row[0][3]['block'];
$block2 = $row[0][4]['block'];
}
An alternative is to restructure the array into something more tidy:
$result = array();
foreach ($array AS $rowId => $row) {
$result[$rowId] = array(
'prem_type' => $row[0][0]['prem_type'],
'phase_name' => $row[0][1]['phase_name'],
'counter' => $row[0][2]['counter'],
'block1' => $row[0][3]['block'],
'block2' => $row[0][4]['block']
);
}
This results in:
Array
(
[0] => Array
(
[prem_type] => 1,
[phase_name] => a1,
[counter] => 2,
[block1] => A,
[block2] => B
)
...
)
Here is the answer:
for($i=0;$i<count($data1);$i++){
for($j=0;$j<count($data1[$i]);$j++){
$prem_type =$data1[$i][$j][0]['prem_type'];
$prem_name= $data1[$i][$j][1]['phase_name'];
$no_of_phase= $data1[$i][$j][2]['counter'];
echo $prem_type." ".$prem_name." ".$no_of_phase."<br>";
for($k=3;$k<count($data1[$i][$j]);$k++){
echo $data1[$i][$j][$k]['unitname']."<br>";
}
}
}

php add some value on specific location in multidimensional array

I have array like this
Array ([0] => Array ( [user_id] => 21 [email] => momod#modara.com [brand] => Array ( [0] => GOFUEL_W [1] => GOFUEL_USD_W ) ) [1] => Array ( [user_id] => 22 [email] => hemisphere#modara.com [brand] => Array ( [0] => GOFUEL_W ) ) [2] => Array ( [user_id] => 23 [email] => madoka#modara.com [brand] => Array ( [0] => GOFUEL_W [1] => GOFUEL_USD_W [2] => GOFUEL_BGD_W ) ) )
i want to locate user_id 22 and put this value "GO_FUEL_SGD_W" on brand, what should i do, so the view of array will look like this
Array ([0] => Array ( [user_id] => 21 [email] => momod#modara.com [brand] => Array ( [0] => GOFUEL_W [1] => GOFUEL_USD_W ) ) [1] => Array ( [user_id] => 22 [email] => hemisphere#modara.com [brand] => Array ( [0] => GOFUEL_W => [1] =>GO_FUEL_SGD_W ) ) [2] => Array ( [user_id] => 23 [email] => madoka#modara.com [brand] => Array ( [0] => GOFUEL_W [1] => GOFUEL_USD_W [2] => GOFUEL_BGD_W ) ) )
Just use loop:
foreach($array as &$item)
{
if(array_key_exists('user_id', $item) &&
$item['user_id']==22 &&
array_key_exists('brand', $item) &&
!in_array('GO_FUEL_SGD_W', $item['brand']))
{
$item['brand'][] = 'GO_FUEL_SGD_W';
}
}
A simple foreach loop will do the job:
foreach($myarray AS &$subarray) {
if($subarray['user_id'] == 22) {
$subarray['brand'][] = "GO_FUEL_SGD_W";
break;
}
}
Working example: http://3v4l.org/8aQMj
You will need to iterate over the array and look for the element you're searching for.
foreach ($array as &$element) {
if ($element['user_id'] != 22)
continue;
$element['brand'][] = "GO_FUEL_SGD_W";
break;
}
With continue; all elements will be skipped, who have $element['user_id'] != 22 (and so none of the code after the continue; will be applied to them!).
Also it will end the loop once the requested element is reached and modified, thanks to break;.
$array= //your array;
foreach($array as $x){
if($x['user_id']=='22'){
$x['brand'][]='GO_FUEL_SGD_W';
break;
}
}

how can i count an element if it appears more than once in the same array?

how can i count an element if it appears more than once in the same array?
I already tried with array_count_values, but it did not work, is it beacuse i got more than one key and value in my array?
This is my output from my array (restlist)
Array (
[0] => Array ( [restaurant_id] => 47523 [title] => cafe blabla)
[1] => Array ( [restaurant_id] => 32144 [title] => test5)
[2] => Array ( [restaurant_id] => 42154 [title] => blabla2 )
[3] => Array ( [restaurant_id] => 32144 [title] => test5)
[4] => Array ( [restaurant_id] => 42154 [title] => blabla2 )
)
I want it to count how many times the same element appears in my array and then add the counted value to my newly created 'key' called hits in the same array.
Array (
[0] => Array ( [restaurant_id] => 47523 [title] => cafe blabla [hits] => 1)
[1] => Array ( [restaurant_id] => 32144 [title] => test5 [hits] => 2)
[2] => Array ( [restaurant_id] => 42154 [title] => blabla2 [hits] => 2)
)
This is how i tried to do what i wanted.
foreach ($cooltransactions as $key)
{
$tempArrayOverRestaurants[]= $key['restaurant_id'];
}
$wordsRestaruants = array_count_values($tempArrayOverRestaurants);
arsort($wordsRestaruants);
foreach ($wordsRestaruants as $key1 => $value1)
{
$temprestaurantswithhits[] = array(
'restaurant_id' => $key1,
'hits' => $value1);
}
foreach ($restlistas $key)
{
foreach ($temprestaurantswithhits as $key1)
{
if($key['restaurant_id'] === $key1['restaurant_id'])
{
$nyspisestedsliste[] = array(
'restaurant_id' => $key['restaurant_id'],
'title' => $key['title'],
'hits' => $key1['hits']);
}
}
}
I know this is probably a noob way to do what i want but i am still new at php..I hope you can help
Just try with associative array:
$input = array( /* your input data*/ );
$output = array();
foreach ( $input as $item ) {
$id = $item['restaurant_id'];
if ( !isset($output[$id]) ) {
$output[$id] = $item;
$output[$id]['hits'] = 1;
} else {
$output[$id]['hits']++;
}
}
And if you want to reset keys, do:
$outputWithoutKeys = array_values($output);

Categories