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()
)
);
?>
Related
I have the following array structure:
$tpl = [
'breadcrumbs' => [
[ 'title' => 'Item Database', 'text' => 'Item Database', 'url' => SITE_DOMAIN.ADMIN_PATH.'/items/' ],
[ 'title' => $category->name, 'text' => $category->name, 'active' => true ]
]
];
I am attempting to insert an element before the last element, so thought I could use array_splice as follows:
if( !is_null($category->category) )
{
array_splice(
$tpl['breadcrumbs'],
1,
0,
[ 'title' => $category->category->name, 'text' => $category->category->name, 'url' => SITE_DOMAIN.ADMIN_PATH.'/items/' ]
);
}
However, this seems to flatten the item I am trying to insert (as per the expected behaviour) and produces the following output:
Array
(
[0] => Array
(
[title] => Item Database
[text] => Item Database
[url] => https://local/qmdepot/admin/items/
)
[1] => Medical Department
[2] => Medical Department
[3] => https://local/qmdepot/admin/items/
[4] => Array
(
[title] => Class 1
[text] => Class 1
[active] => 1
)
)
While the expected output should be:
Array
(
[0] => Array
(
[title] => Item Database
[text] => Item Database
[url] => https://local/qmdepot/admin/items/
)
[1] => Array
(
[title] => Medical Department
[text] => Medical Department
[url] => https://local/qmdepot/admin/items/
)
[2] => Array
(
[title] => Class 1
[text] => Class 1
[active] => 1
)
)
I am able to achieve this using the following code, but it feels a little hacky to me:
# Set up the breadcrumbs:
if( !is_null($category->category) )
{
$tpl['breadcrumbs'][2] = $tpl['breadcrumbs'][1];
$tpl['breadcrumbs'][1] = [ 'title' => $category->category->name, 'text' => $category->category->name, 'url' => SITE_DOMAIN.ADMIN_PATH.'/items/' ];
}
Is there any way to insert an array item into a multi-dimensional array at a specified index without writing a custom function or using the hack above?
Since the item you want to insert is an array, and array_splice takes an array of items, put your array in an array.
Also since you want to insert something before the last element you can use a negative number for the offset to count backward from the end. (The effect is the same with the data you've got, but matters on arrays of different sizes.)
array_splice(
$tpl['breadcrumbs'],
-1,
0,
[[ 'title' => $category->category->name, 'text' => $category->category->name, 'url' => SITE_DOMAIN.ADMIN_PATH.'/items/' ]]
);
Been fighting the whole night. Giving up. I have an adjacent table in mysql:
id, parentid,name,design,path,sort
The depth is maximum four and using mysql query, I print out the results to UL list successfully. From there, items are added, sorted and edited as well as removed. Then when button is clicked, I send the result back to php. The data been sent is JSON and it does get recieved.
json_decode() gives the following sample:
Array ( [0] => Array ( [cls] => [path] => # [id] => 1 [name] =>BLOCKA ) [1] => Array ( [cls] => [path] => # [id] => 2 [name] => BLOCKB [children] => Array ( [0] => Array ( [cls] => [path] => # [id] => 3 [name] => CLASSB1 [children] => Array ( [0] => Array ( [cls] => [path] => # [id] => 7 [name] => CLASSB12 ) ) ) [1] => Array ( [cls] => [path] => # [id] => 4 [name] => CLASSSB13 [children] => Array ( [0] => Array ( [cls] => [path] => # [id] => 5 [name] => CLASSB4 ) [1] => Array ( [cls] => [path] => # [id] => 6 [name] => CLASSB5 ) ) ) ) ) )
Graphically:
BLOCKA
BLOCKB
CLASSB1
CLASSB3
...
I am using jquery.nested
Now my problem is looping through the array, getting id of the parent then add child.
The closest I came with is
function dissect($blocks) {
if (!is_array($blocks)) {
echo $blocks;
return;
}
foreach($blocks as $block) {
dissect($block);
}
}
It does process each element but not in the way I want. Sorry for my broken english...any help would be appreciated.
First iterate through blocks getting the parent, if children exists in parent block, loop through the children.
There might be other better way to implement this, you can try below code:
$blocks = array (
"0" => array (
"cls" => "",
"path" => array(
"id" => 1,
"name" =>"BLOCKA",
)
),
"1" => array (
"cls" => "",
"path" => array(
"id" => 2,
"name" => "BLOCKB" ,
"children" => array (
"0" => array (
"cls" => "",
"path" => array(
"id" => 3,
"name" => "CLASSB1" ,
"children" => array (
"0" => array (
"cls" => "",
"path" => array(
"id" => 7,
"name" => "CLASSB12" ,
),
),
),
),
),
"1" => array (
"cls" => "",
"path" => array(
"id" => 4,
"name" => "CLASSSB13" ,
"children" => array (
"0" => array (
"cls" => "",
"path" => array(
"id" => 5,
"name" => "CLASSB4" ,
),
),
"1" => array (
"cls" => "",
"path" => array(
"id" => 6,
"name" => "CLASSB5",
),
),
),
),
),
),
),
),
) ;
echo "<pre>";
/*loop through blocks*/
foreach ($blocks as $key => $block) {
echo $block['path']['name'].'<br/>'; /* echo parent*/
if (isset($block['path']['children'])) {
loopChildren($block['path']['children']); /* children loop*/
}
}
/*Loop through childrens*/
function loopChildren($childrens, $prefix = '-')
{
foreach ($childrens as $key => $child) {
getChild($child, $prefix);
}
}
/*Get the child and loop sub-children if exist*/
function getChild($child, $prefix='-')
{
echo $prefix. $child['path']['name'].'<br/>'; /*echo child*/
if (isset($child['path']['children'])) {
$prefix .= '-';
loopChildren($child['path']['children'], $prefix); /* sub-children loop*/
}
}
echo "</pre>";
The output:
BLOCKA
BLOCKB
-CLASSB1
--CLASSB12
-CLASSSB13
--CLASSB4
--CLASSB5
thanks for your tip. It guided me to an answer that worked for me. I ended up using two functions. The error was "index out of bound"...here is what I did now...with calls to the mysql table:
$response = json_decode($_POST['s'], true); // decoding received JSON to array
if(is_array($response)){
//start saving now
$order=1;
foreach ($response as $key => $block) {
//0 is for blocks: no parent id needed
$parentid=$this->Blocks_model->insertblock($block['name'],$block['cls'],0,$block['path'],$order);
if (isset($block['children'])) {
$this->childblocks($parentid,$block['children']);
}
$order++;
}
}
private function childblocks($parentid,$e){
$order=1;
foreach ($e as $key => $block) {
$parentid=$this->Blocks_model->insertblock($block['name'],$block['cls'],0,$block['path'],$order);
if (isset($block['children'])) {
$this->childblocks($parentid,$block['children']);
}
$order++;
}
}
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'];
}
if anyone could please help me here I would be eternally grateful as I've spent about 2 full days now trying to get this to work. I want to take two multidimensional arrays and compare them, then remove any duplicate records.
The scenario is: The values in array2 have already been assigned to a user's profile. The values in array1 are ALL of the available values that the user can choose from. I want to compare the two so that only the ones not already assigned are given as an option (left in the array)...
$array1 = array(
[0] => array( [id] => 3 [name] => Eye Colour )
[1] => array( [id] => 1 [name] => Hair Colour )
[2] => array( [id] => 5 [name] => Hair Length )
[3] => array( [id] => 4 [name] => Height )
);
$array2 = array(
[0] => array( [attribute_id] => 3 [name] => Eye Colour [active] => 1 )
[1] => array( [attribute_id] => 5 [name] => Hair Length [active] => 1 ) )
);
PHP's array_diff() function doesn't work with multidimensional arrays, and I've had a good search around but can't seem to find anything that works for me!
The result based on the above two arrays should be:
$array1 = array(
[0] => array( [id] => 1 [name] => Hair Colour )
[1] => array( [id] => 4 [name] => Height )
);
The [active] field is irrelevant, so I just need it to compare the ID and the Name fields. I realise that the name of the two id fields is different, but it would be a pain to change them as they are database column names.
It needs to completely remove the array, not just the values. I've had issues with previous attempts where it leaves array( ) in there and then this causes issues when I'm looping through the array generating the fields that the user can choose from.
Please help. I will buy you many beers! :)
Thanks,
Steve
I don't know how to do it with any built-in PHP function but here's a custom one:
$array1 = array(
array( 'id' => 3, 'name' => 'Eye Colour' ),
array( 'id' => 1, 'name' => 'Hair Colour' ),
array( 'id' => 5, 'name' => 'Hair Length' ),
array( 'id' => 4, 'name' => 'Height' ),
);
$array2 = array(
array( 'attribute_id' => 3, 'name' => 'Eye Colour', 'active' => 1 ),
array( 'attribute_id' => 5, 'name' => 'Hair Length', 'active' => 1 )
);
// function to remove duplicates
function myArrayDiff($array1, $array2) {
// loop through each item on the first array
foreach ($array1 as $key => $row) {
// loop through array 2 and compare
foreach ($array2 as $key2 => $row2) {
if ($row['id'] == $row2['attribute_id']) {
// if we found a match unset and break out of the loop
unset($array1[$key]);
break;
}
}
}
return array_values($array1);
}
$array3 = myArrayDiff($array1, $array2);
print_r($array3);
/* result:
Array
(
[0] => Array
(
[id] => 1
[name] => Hair Colour
)
[1] => Array
(
[id] => 4
[name] => Height
)
)
*/
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
)
);