PHP How to restructure an array? - php

I have an array that I'd like to restructure. I want to group items by turn. I can figure out how to extract data from the array using foreach($arr['history'] as $obj) my issue is with populating a new array using a loop.
Currently it looks like this:
Array (
[history] => Array (
[id] => 23452435
[legend] => Array (
[0] => Array (
[player] => me
[turn] => 1
[card] => Array (
[name] => foo
)
)
[1] => Array (
[player] => me
[turn] => 1
[card] => Array (
[name] => bar
)
)
[2] => Array (
[player] => opponent
[turn] => 1
[card] => Array (
[name] => derp
)
)
[3] => Array (
[player] => opponent
[turn] => 2
[card] => Array (
[name] => hoo
)
)
)
))
I want it to look like the following, but I can't figure out how to automatically create and populate this structure. This is an array with a sub-array for each turn, containing an array for me and opponent
Array (
[0] => Array (
[me] => Array (
[0] => foo
[1] => bar
)
[opponent] = Array (
[0] => derp
)
)
[1] => Array (
[me] => Array ()
[opponent] => Array (
[0] => hoo
)
))
Thanks.
Edit:
This is what I needed. Thanks for the answers.
$result = [];
foreach ($arr['history'] as $historyItem) {
foreach ($historyItem['legend'] as $list) {
$result[$list['turn']][$list['player']][] = $list['card']['name'];
}
}

Try this:
$result = [];
foreach ($data['history']['legend'] as $list) {
$result[$list['turn']-1][$list['player']][] = $list['card']['name'];
}
Fiddle it! http://ideone.com/BtKOKJ

You can just start adding data to the new array. PHP is extremely forgiving.
$historyByTurns = array();
foreach ($arr['history'] as $historyItem) {
foreach ($historyItem['legend'] as $legendItem) {
$turn = $legendItem['turn'];
$player = $legendItem['player'];
if (!array_key_exists($turn, $historyByTurns)) {
$historyByTurns[$turn] = array();
}
if (!array_key_exists($player, $historyByTurns[$turn])) {
$historyByTurns[$turn][$player] = array();
}
foreach ($legendItem as $card) {
$historyByTurns[$turn][$player][] = $card['name'];
}
}
}
You will have to test it, as I have no way to do that ATM.

Related

Merge an associative array with comma if one index is same and other is different

I have an array like this:
Array
(
[0] => Array
(
[id] => 10
[field] => new
[value] => pqr
)
[1] => Array
(
[id] => 14
[field] => test
[value] => abc
)
[2] => Array
(
[id] => 17
[field] => test
[value] => xyz
)
)
Now I want to merge this array with field name with id and value will be comma separated. So my new array will look like:
Array
(
[0] => Array
(
[id] => 10
[field] => new
[value] => pqr
)
[1] => Array
(
[id] => 14,17
[field] => test
[value] => abc,xyz
)
)
Can we do this with any php inbuilt function.
I don't know of any built in function to do this, but it's pretty trivial with a simple foreach loop.
String Concatenation Approach
$new_array = [];
foreach($array1 as $arr) {
$field = $arr['field'];
$id = $arr['id'];
$value = $arr['value'];
//we use $field as $new_array keys so we can combine values
if(!array_key_exists($field, $new_array)) {
//key doesn't exist in new array, so create it
$new_array[$field] = $arr;
} else {
//key exists in new array, append new values
$new_array[$field]['id'] .= ",{$id}";
$new_array[$field]['value'] .= ",{$value}";
}
}
//reset array keys back to sequential
$new_array = array_values($new_array);
Output of $new_array would be
Array
(
[0] => Array
(
[id] => 10
[field] => new
[value] => pqr
)
[1] => Array
(
[id] => 14,17
[field] => test
[value] => abc,xyz
)
)
Normalized Array Approach
$new_array = [];
foreach($array1 as $arr) {
$field = $arr['field'];
$id = $arr['id'];
$value = $arr['value'];
//we use $field as $new_array keys so we can combine values
if(!array_key_exists($field, $new_array)) {
//key doesn't exist in new array, so create it
$new_array[$field] = ['id' => [$id], 'field' => $field, 'value' => [$value]];
} else {
//key exists in new array, append new values
$new_array[$field]['id'][] = $id;
$new_array[$field]['value'][] = $value;
}
}
//reset array keys back to sequential
$new_array = array_values($new_array);
Output of $new_array would be
Array
(
[0] => Array
(
[id] => Array
(
[0] => 10
)
[field] => new
[value] => Array
(
[0] => pqr
)
)
[1] => Array
(
[id] => Array
(
[0] => 14
[1] => 17
)
[field] => test
[value] => Array
(
[0] => abc
[1] => xyz
)
)
)

How do i make one array out of two arrays containing different values

I have two arrays, one called fetched_services and one called fetched_companies, they look like this:
fetched_services
(
[1] => Array
(
[id] => 11
[child_services] => Array
(
[0] => Array
(
[id] => 153
)
[1] => Array
(
[id] => 137
)
[2] => Array
(
[id] => 138
)
)
)
)
fetched_companies
(
[0] => stdClass Object
(
[services] => Array
(
[0] => 25
[1] => 102
)
)
)
What i want to achieve is to end up with an array like fetched_services but only having child_services with id of fetched_companies["services"].
What i have tried is this:
$services = [];
$isFound = false;
foreach ($fetched_services as $fetched_service) {
foreach ($fetched_service["child_services"] as $fetched_child_service) {
$fetched_service["child_services"] = [];
foreach ($fetched_companies as $fetched_company) {
if( (in_array($fetched_child_service["id"],$fetched_company->services)) ) {
$fetched_service["child_services"][] = $fetched_child_service;
$isFound = true;
}
}
if($isFound) {
$services[] = $fetched_service;
$isFound = false;
}
}
}
This outputs this:
Array
(
[0] => Array
(
[id] => 11
[child_services] => Array
(
[0] => Array
(
[id] => 116
)
)
)
[1] => Array
(
[id] => 11
[child_services] => Array
(
[0] => Array
(
[id] => 117
)
)
)
)
As you can see the resulting array have two arrays containing same id but the child_services are different.
What i want to end up with is this:
Array
(
[0] => Array
(
[id] => 11
[child_services] => Array
(
[0] => Array
(
[id] => 116
)
)
(
[0] => Array
(
[id] => 117
)
)
)
)
What am i doing wrong here? Thanks!
Your question is a bit unclear (I'll edit/delete this if/when you clarify, see my comment above), but you could probably make use of array_filter by only keeping services that are present in said list (via in_array):
$result = array_filter(
$fetched_services['child_services'],
fn(array $child_service): bool => in_array($child_service['id'], $fetched_companies[0]->services, true)
);
Demo

Sequence issue with nested foreach loop php

I have two array. array one and array two. I want to merge these array into single array with key. My output result is valid but sequence is not correct.
Array one
Array
(
[0] => test-685f1e7bc357187e449479d627100102
[1] => test-685f1e7bc357187e449479d627d29390
)
Array two
Array
(
[0] => DF955298-A664-4FA7-9586-FCD4CF977777
[1] => DF955298-A664-4FA7-9586-FCD4CF988888
)
Expected Result
Array
(
[0] => Array
(
[key] => test-685f1e7bc357187e449479d627100102
[uuid] => DF955298-A664-4FA7-9586-FCD4CF977777
)
[1] => Array
(
[key] => test-685f1e7bc357187e449479d627d29390
[uuid] => DF955298-A664-4FA7-9586-FCD4CF988888
)
)
My code is for that result is mentioned below:
$record = array();
foreach ($keys_array as $key => $all_key) {
foreach ($uuid_array as $uuid_key => $all_uuid) {
$record[$key]['key'] = $all_key;
$record[$uuid_key]['uuid'] = $all_uuid;
}
}
My output sequence is not valid. Where is the problem
Array
(
[0] => Array
(
[key] => test-685f1e7bc357187e449479d627100102
[uuid] => DF955298-A664-4FA7-9586-FCD4CF977777
)
[1] => Array
(
[uuid] => test-685f1e7bc357187e449479d627d29390
[key] => DF955298-A664-4FA7-9586-FCD4CF988888
)
)
Simple solution:
$record = array();
foreach ($keys_array as $key => $all_key) {
$record[] = [
'key' => $all_key,
// get value under the same key from `$uuid_array`
'uuid' => $uuid_array[$key],
];
}

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>";
}
}
}

compare two associative array and display the difference

I have the following Two array results coming from MySQL query result.
Array One (Orignal-Data):
Array
(
[w_a] => Array
(
[0] => Array
(
[cod] => CRR
[pr] => LL
[aid] => VM2254
[gender] => m
[title] =>
)
)
[w_a_ml] => Array
(
)
[w_a_ol] => Array
(
)
[w_a_rl] => Array
(
[0] => Array
(
[rol] => 1
)
)
)
Array Two (Changed-Data)
Array
(
[w_a] => Array
(
[0] => Array
(
[cod] => CRR
[pr] => LL
[aid] => VM2254
[gender] => f
[title] => Mr
)
)
[w_a_ml] => Array
(
[0] => Array
(
[wl] => 255
[care] => Sahan
[heigh] =>
[adam] =>
[instance] => Look
)
)
[w_a_ol] => Array
(
)
[w_a_rl] => Array
(
[0] => Array
(
[rol] => 1
)
)
)
What I wan to achieve from the above two array is to compare and show the result in table format or Inside Form To each Field (Original and New-Change) like below.
FiledsN Original New Change
title Empty Mr
Wl Empty 255
Care Empty Sahan
gender m f
instance Empty Look
I've tried making the array a single array using this function:
function array_single($arr) {
if (!is_array($arr)) {
return FALSE;
}
$res = array();
foreach ($arr as $keys => $values) {
if (is_array($values)) {
$res = array_merge($res, array_single($values));
} else {
$res[$keys] = $values;
}
}
return $res;
}
And then comparing using this:
function diff($new,$old) {
$del=array_diff_assoc($old,$new);
$add=array_diff_assoc($new,$old);
return $diff=array("old"=>$del, "new"=>$add);
}

Categories