I'm trying to create a tables with information from two arrays. Here are the two arrays:
First array, for table headers
Array
(
[0] => Color
[1] => Length
[2] => Waist
)
Second array, the one that needs modification
Array
(
[0] => Array
[0] => green [1] => Color
[1] => Array
[0] => 23 [1] => Length
)
Array
(
[0] =>
)
Array
(
[0] => Array
[0] => 23 [1] => Length
[1] => Array
[0] => 24 [1] => Waist
)
Array needs to look like this:
Array
(
[0] => Array
[0] => green [1] => Color
[1] => Array
[0] => 23 [1] => Length
[2] => Array
[0] => [1] => Waist
Array
(
[0] => Array
[0] => [1] => Color
[1] => Array
[0] => [1] => Length
[2] => Array
[0] => [1] => Waist
Array
(
[0] => Array
[0] => [1] => Color
[1] => Array
[0] => 23 [1] => Length
[2] => Array
[0] => 24 [1] => Waist
So the point is that the keys in the first level needs to match the keys in the array that makes the table headers, where [1] one the second level has the same value as the table header. Any ideas?
After some feedback, an alternative acceptable output array structure would be:
array(
array(
'Color' => 'green',
'Length' => 23,
'Waist' => null
),
array(
'Color' => null,
'Length' => null,
'Waist' => null
),
array(
'Color' => null,
'Length' => 23,
'Waist' => 24
)
)
You have a complex array structure for an easy set of data. Could your final array work better like this?
$data = array(
array(
'Color' => 'green',
'Length' => 23,
'Waist' => NULL
),
array(
'Color' => NULL,
'Length' => NULL,
'Waist' => NULL
),
array(
'Color' => NULL,
'Length' => 23,
'Waist' => 24
)
);
If you're dead set on your structure, though, this should work:
function format_my_array($keys, $malformed) {
foreach ($malformed as $key => $fragments) {
$temp = array(
'Color' => NULL,
'Length' => NULL,
'Waist' => NULL
);
foreach ($fragments as $fragment) {
if (isset($fragment[1])) {
switch($fragment[1]) {
case 'Length':
$temp['Length'] = $fragment[1];
break;
case 'Waist':
$temp['Waist'] = $fragment[1];
break;
default:
$temp['Color'] = $fragment[1];
break;
}
}
}
$malformed[$key] = array(
array($temp['Color'], 'Color'),
array($temp['Length'], 'Length'),
array($temp['Waist'], 'Waist')
);
}
return $malformed;
}
Generate the default values (once) as a re-usable array, then iterate your input data and overwrite the default values with each item's set of "attributes".
Code: (Demo) (PHP7.4+ Demo)
$headers = ['Color', 'Length', 'Waist'];
$data = [
[
['green', 'Color'],
['23', 'Length'],
],
[],
[
['23', 'Length'],
['24', 'Waist'],
],
];
$defaults = array_fill_keys($headers, null);
var_export(
array_map(
function($item) use($defaults) {
return array_replace($defaults, array_column($item, 0, 1));
},
$data
)
);
Related
I need to convert the below 2d array in to specified 2d array format. Array contains multiple parent and multiple child array. Also, have tried to convert the code, but am not getting the expected output.
This is the code what i have tried,
$a1 = array(
'0' =>
array(
'banner_details' =>
array(
'id' => 2,
'section_id' => 24
),
'slide_details' =>
array(
0 => array(
'id' => 74,
'name' => 'Ads1'
),
1 => array(
'id' => 2,
'name' => 'Ads2'
)
)
),
'1' =>
array(
'banner_details' =>
array(
'id' => 106,
'section_id' => 92
),
'slide_details' =>
array(
0 => array(
'id' => 2001,
'name' => 'Adv1'
),
1 => array(
'id' => 2002,
'name' => 'Adv2'
)
)
)
);
$s = [];
for($i = 0; $i<2; $i++) {
foreach($a1[$i]['slide_details'] as $vs){
$s[] = $vs;
}
}
My output:
Array
(
[0] => Array
(
[id] => 74
[name] => Ads1
)
[1] => Array
(
[id] => 2
[name] => Ads2
)
[2] => Array
(
[id] => 2001
[name] => Adv1
)
[3] => Array
(
[id] => 2002
[name] => Adv2
)
)
Expected output:
Array
(
[24] => Array
(
[0] => 74
[1] => 2
)
[92] => Array
(
[0] => 2001
[1] => 2002
)
)
please check the above code and let me know.
Thanks,
You can apply next simple foreach loop with help of isset() function:
foreach($a1 as $data){
if (isset($data['banner_details']['section_id'])){
$s[$data['banner_details']['section_id']] = [];
if (isset($data['slide_details'])){
foreach($data['slide_details'] as $row){
$s[$data['banner_details']['section_id']][] = $row['id'];
}
}
}
}
Demo
If you know that indexes like banner_details or slide_details or section_id will be there always then you can skip isset() in if statements.
You can use array_column function for simple solution:
$result = [];
foreach ($a1 as $item)
{
$result[$item['banner_details']['section_id']] = array_column($item['slide_details'], 'id');
}
var_dump($result);
How can we find the count of duplicate elements in a multidimensional array and concat of ids ?
I have an array of skill names with feed ids. I need to count skill name and concat of feed ids.
Array
(
[0] => Array
(
[skill_name] => PHP
[feed_id] => 100
)
[1] => Array
(
[skill_name] => CSS
[feed_id] => 105
)
[2] => Array
(
[skill_name] => Php
[feed_id] => 110
)
[3] => Array
(
[skill_name] => Php
[feed_id] => 111
)
[4] => Array
(
[skill_name] => CSS
[feed_id] => 112
)
[5] => Array
(
[skill_name] => Javascript
[feed_id] =>114
)
}
Output should be like below.
Array
(
[0] => Array
(
[skill_name] => PHP
[feed_id] => 100, 110, 111
[count]=>3
)
[1] => Array
(
[skill_name] => CSS
[feed_id] => 105, 112
[count]=>2
)
[2] => Array
(
[skill_name] => Javascript
[feed_id] => 114
[count]=>1
)
}
Thanks in advance!!
//Assumption: Input is in $in
//Step 1: Cumulate
$tmp=array();
foreach ($in as $skill) {
if (isset($tmp[$skill['skill_name']]))
$tmp[$skill['skill_name']][]=$skill['feed_id'];
else
$tmp[$skill['skill_name']]=array($skill['feed_id']);
}
//Step 2: Fix up desired output format
$out=array();
foreach ($tmp as $k=>$v)
$out[]=array(
'skill_name' => $k,
'feed_id' => implode(', ', $v),
'count' => sizeof($v)
);
//Result is in $out
This is perfectly achievable with a single loop using temporary keys and simple concatenation and incrementation.
Code: (Demo)
$array = [
['skill_name' => 'PHP', 'feed_id' => 100],
['skill_name' => 'CSS', 'feed_id' => 105],
['skill_name' => 'Php', 'feed_id' => 110],
['skill_name' => 'Php', 'feed_id' => 111],
['skill_name' => 'CSS', 'feed_id' => 112],
['skill_name' => 'Javascript', 'feed_id' => 114]
];
foreach ($array as $row) {
$upperSkill = strtoupper($row['skill_name']);
if (!isset($result[$upperSkill])) {
$result[$upperSkill] = $row + ['count' => 1]; // plus acts as array_merge here
} else {
$result[$upperSkill]['feed_id'] .= ",{$row['feed_id']}"; // concatenate
++$result[$upperSkill]['count']; // increment
}
}
var_export(array_values($result)); // reindex and display
Output:
array (
0 =>
array (
'skill_name' => 'PHP',
'feed_id' => '100,110,111',
'count' => 3,
),
1 =>
array (
'skill_name' => 'CSS',
'feed_id' => '105,112',
'count' => 2,
),
2 =>
array (
'skill_name' => 'Javascript',
'feed_id' => 114,
'count' => 1,
),
)
I have 2 multidimensional arrays that I am working with:
$arr1 =
Array
([type] => characters
[version] => 5.6.7.8
[data] => Array
([Char1] => Array
([id] => 1
[name] =>Char1
[title] =>Example
[tags] => Array
([0] => DPS
[1] => Support))
[Char2] => Array
([id] => 2
[name] =>Char2
[title] =>Example
[tags] => Array
([0] => Tank
[1] => N/A)
)
)
etc...
$arr2=
Array
([games] => Array
([gameId] => 123
[gameType => Match
[char_id] => 1
[stats] => Array
([damage] => 55555
[kills] => 5)
)
([gameId] => 157
[gameType => Match
[char_id] => 2
[stats] => Array
([damage] => 12642
[kills] => 9)
)
etc...
Basically, I need almost all the data in $arr2... but only the Char name from $arr1. How could I merge or add the $arr1['name'] key=>value into $arr2 where $arr1['id'] is equal to $arr2['char_id'] as the "id" field of each array is the same number.
I've attempted using array_merge and array_replace, but I haven't come up with any working solutions. This is also all data that I am receiving from a 3rd party, so I have no control on initial array setup.
Thanks for any help or suggestions!
Actually, this is quite straighforward. (I don't think there a built-in function that does this.)
Loop $arr2 and under it loop also $arr1. While under loop, just add a condition that if both ID's match, add that particular name to $arr2. (And use some referencing & on $arr2)
Consider this example:
// your data
$arr1 = array(
'type' => 'characters',
'version' => '5.6.7.8',
'data' => array(
'Char1' => array(
'id' => 1,
'name' => 'Char1',
'title' => 'Example',
'tags' => array('DPS', 'Support'),
),
'Char2' => array(
'id' => 2,
'name' => 'Char2',
'title' => 'Example',
'tags' => array('Tank', 'N/A'),
),
),
);
$arr2 = array(
'games' => array(
array(
'gameId' => 123,
'gameType' => 'Match',
'char_id' => 1,
'stats' => array('damage' => 55555, 'kills' => 5),
),
array(
'gameId' => 157,
'gameType' => 'Match',
'char_id' => 2,
'stats' => array('damage' => 12642, 'kills' => 9),
),
),
);
foreach($arr2['games'] as &$value) {
$arr2_char_id = $value['char_id'];
// loop and check against the $arr1
foreach($arr1['data'] as $element) {
if($arr2_char_id == $element['id']) {
$value['name'] = $element['name'];
}
}
}
echo '<pre>';
print_r($arr2);
$arr2 should look now like this:
Array
(
[games] => Array
(
[0] => Array
(
[gameId] => 123
[gameType] => Match
[char_id] => 1
[stats] => Array
(
[damage] => 55555
[kills] => 5
)
[name] => Char1 // <-- name
)
[1] => Array
(
[gameId] => 157
[gameType] => Match
[char_id] => 2
[stats] => Array
(
[damage] => 12642
[kills] => 9
)
[name] => Char2 // <-- name
)
)
)
Iterate over $arr2 and add the data to it from the matching $arr1 array value:
$i = 0;
foreach($arr2['games'] as $arr2Game){
$id = $arr2Game['char_id'];
$arr2['games'][$i]['name'] = $arr1['data'][$id]['name'];
$i++;
}
Have not tested this code.
If I'm understanding you correctly, you want to add a name index to each of the arrays within the $arr2['games'] array.
foreach($arr2['games'] as $key => $innerArray)
{
$arr2['games'][$key]['name'] = $arr1['data']['Char'.$innerArray['char_id']]['name'];
}
I am trying to get this array output in this format to be used by Chart.js in Yii.
This is the array I need to get:
Array
(
[0] => Array
(
[value] => 50
[color] => rgba(66,66,66,1)
[label] => Hunde
)
[1] => Array
(
[value] => 25
[color] => rgba(66,66,66,1)
[label] => Katzen
)
)
This is the code that produces the above array:
$array = array(
array(
"value" => 50,
"color" => "rgba(66,66,66,1)",
"label" => "Hunde"
),
array(
"value" => 25,
"color" => "rgba(66,66,66,1)",
"label" => "Katzen"
),
);
This is the code I am typing:
protected function modulesArray(){
$modules = Module::model()->findAll();
foreach ($modules as $module) {
$array[] = array("value" => 50, "color" => "$module->color",
"label" => "$module->category");
}
return $array;
}
And this is the array output I am getting:
Array
(
[0] => Array
(
[value] => 50
[color] => #b83333
[label] => Tyres
)
[1] => Array
(
[value] => 50
[color] => #3276eb
[label] => Hydraulics
)
)
The thing is, I don't seem to see any difference except for the color (which is allowed to be put in hex values), however, when I merge my array to the above array, the charts seem to load fine. Does this mean the array output that I get is fine?
I am trying to get my head around it as everything seems fine! I have no clue what am I doing wrong.
P.S : -
This is the widget section code:
<?php
$this->widget(
'ext.chartjs.widgets.ChPolar',
array(
'width' => 250,
'height' => 250,
'htmlOptions' => array(),
'drawLabels' => true,
'datasets' => $modulesArray,
'options' => array()
)
);
?>
I have the following array:
items = array(
'note' => array(),
'text' => array(),
'year' => array()
)
So I have:
[note] => Array
(
[0] => 'note1'
[1] => 'note2'
[2] => 'note3'
),
[text] => Array
(
[0] => 'text1'
[1] => 'text2'
[2] => 'test3'
),
[year] => Array
(
[0] => '2002'
[1] => '2000'
[2] => '2011'
)
And I would like to arrange the above arrays by year. but when moving elements I would like to move the corresponding elements in other arrays(note,text).
For example:
[note] => Array
(
[2] => 'note3'
[0] => 'note1'
[1] => 'note2'
),
[text] => Array
(
[2] => 'text3'
[0] => 'text1'
[1] => 'test2'
),
[year] => Array
(
[2] => '2011'
[0] => '2002'
[1] => '2000'
)
I would first extract the year part and sort it by value, while still maintaining the key, using arsort():
$yearData = $array['year'];
arsort($yearData);//sort high-to-low by value, while maintain it's key.
Finally, sort the data using this newly sorted year:
$newArray['note'] = array();
$newArray['text'] = array();
$newArray['year'] = array();
foreach($yearData as $key => $value){
$newArray['note'][$key] = $array['note'][$key];
$newArray['text'][$key] = $array['text'][$key];
$newArray['year'][$key] = $array['year'][$key];
}
FYI, there are a bunch of functions that deal with sorting arrays in PHP.
I think a better organization to your array would be something like this:
[0] => Array(
'note' => note1, 'text' => 'text1', 'year' => '2002)
[1] => Array(
'note' => note2, 'text' => 'text2', 'year' => '2000)
[2] => Array(
'note' => note3, 'text' => 'text4', 'year' => '2011)
This way, each related item stays together and it's easier to sort them by the desired type.
$items = array(
array(
'note' => value,
'text' => value,
'year' => value
),
array(
'note' => value,
'text' => value,
'year' => value
)
)