Overlapping Associative Arrays - php

I need to overlap data from multiple associative arrays with the following considerations:
If a matching key exists, overwrite it
If a key exists but doesn't match, append new value to that element
If neither of the above, create an element to store the value
Take for example the following structures:
<?php
for ($i = 0; $i < 10; $i++) {
$table["table_$i"] = array(
"cell_0" => array(
'row' => 12,
'column' => 5
)
);
}
for ($i = 4; $i < 12; $i++) {
$table["table_$i"] = array(
"cell_0" => array(
'row' => 9,
'column' => 8
)
);
}
for ($i = 5; $i < 15; $i++) {
$table["table_$i"] = array(
"cell_1" => array(
'row' => 4,
'column' => 1
)
);
}
?>
The desired output would look like this:
{"table_0":{"cell_0":{"row":12,"column":5}},"table_1":{"cell_0":{"row":12,"column":5}},"table_2":{"cell_0":{"row":12,"column":5}},"table_3":{"cell_0":{"row":12,"column":5}},"table_4":{"cell_0":{"row":9,"column":8}},"table_5":{"cell_0":{"row":9,"column":8},"cell_1":{"row":4,"column":1}},"table_6":{"cell_0":{"row":9,"column":8},"cell_1":{"row":4,"column":1}},"table_7":{"cell_1":{"row":4,"column":1}},"table_8":{"cell_0":{"row":9,"column":8},"cell_1":{"row":4,"column":1}},"table_9":{"cell_0":{"row":9,"column":8},"cell_1":{"row":4,"column":1}},"table_10":{"cell_0":{"row":9,"column":8},"cell_1":{"row":4,"column":1}},"table_11":{"cell_0":{"row":9,"column":8},"cell_1":{"row":4,"column":1}},"table_12":{"cell_1":{"row":4,"column":1}},"table_13":{"cell_1":{"row":4,"column":1}},"table_14":{"cell_1":{"row":4,"column":1}}}
Take note from the desired output that the value of cell_0 doesn't replace the value of cell_1: I couldn't get the desired output using array_merge() in this case.
Any help would be appreciated--thanks!

Check array_merge and array_unique php functions.

Related

PHP - add values to already existing array

I have a already defined array, containing values just like the one below:
$arr = ['a','b','c'];
How could one add the following using PHP?
$arr = [
'a' => 10,
'b' => 5,
'c' => 21
]
I have tried:
$arr['a'] = 10 but it throws the error: Undefined index: a
I am surely that I do a stupid mistake.. could someone open my eyes?
Full code below:
$finishes = []; //define array to hold finish types
foreach ($projectstages as $stage) {
if ($stage->finish_type) {
if(!in_array($stage->finish_type, $finishes)){
array_push($finishes, $stage->finish_type);
}
}
}
foreach ($projectunits as $unit) {
$data[$i] = [
'id' => $unit->id,
'project_name' => $unit->project_name,
'block_title' => $unit->block_title,
'unit' => $unit->unit,
'core' => $unit->core,
'floor' => $unit->floor,
'unit_type' => $unit->unit_type,
'tenure_type' => $unit->tenure_type,
'floors' => $unit->unit_floors,
'weelchair' => $unit->weelchair,
'dual_aspect' => $unit->dual_aspect
];
$st = array();
$bs = '';
foreach ($projectstages as $stage) {
$projectmeasure = ProjectMeasure::select('measure')
->where('project_id',$this->projectId)
->where('build_stage_id', $stage->id)
->where('unit_id', $unit->id)
->where('block_id', $unit->block_id)
->where('build_stage_type_id', $stage->build_stage_type_id)
->first();
$st += [
'BST-'.$stage->build_stage_type_id => ($projectmeasure ? $projectmeasure->measure : '0')
];
if (($stage->is_square_meter == 0) && ($stage->is_draft == 0)) {
$height = ($stage->height_override == 0 ? $unit->gross_floor_height : $stage->height_override); //08.14.20: override default height if build stage type has it's own custom height
$st += [
'BST-sqm-'.$stage->build_stage_type_id => ($projectmeasure ? $projectmeasure->measure * $height: '0')
];
if ($stage->finish_type) {
$finishes[$stage->finish_type] += ($projectmeasure ? $projectmeasure->measure * $height: '0') * ($stage->both_side ? 2 : 1); //error is thrown at this line
}
} else {
if ($stage->finish_type) {
$finishes[$stage->finish_type] += ($projectmeasure ? $projectmeasure->measure : '0');
}
}
}
$data[$i] = array_merge($data[$i], $st);
$data[$i] = array_merge($data[$i], $finishes[$stage->finish_type]);
$i++;
}
The above code is used as is and the array $finishes is the one from the first example, called $arr
You're using += in your real code instead of =. That tries to do maths to add to an existing value, whereas = can just assign a new index with that value if it doesn't exist.
+= can't do maths to add a number to nothing. You need to check first if the index exists yet. If it doesn't exist, then assign it with an initial value. If it already exists with a value, then you can add the new value to the existing value.
If you want to convert the array of strings to a collection of keys (elements) and values (integers), you can try the following:
$arr = ['a','b','c'];
$newVals = [10, 5, 21];
function convertArr($arr, $newVals){
if(count($arr) == count($newVals)){
$len = count($arr);
for($i = 0; $i < $len; $i++){
$temp = $arr[$i];
$arr[$temp] = $newVals[$i];
unset($arr[$i]);
}
}
return $arr;
}
print_r(convertArr($arr, $newVals));
Output:
Array ( [a] => 10 [b] => 5 [c] => 21 )

PHP Excel from array merge cells

I export a table of participants. I have a form for the participants, where I have dynamically generated section for choosing meals. It comes from array like this:
$days = array(
array(
'title' => 'Saturday',
'meals' => array(
array(
'title' => 'Brf',
'price' => 25
),
array(
'title' => 'Lnch',
'price' => 60
),
array(
'title' => 'Dnr',
'price' => 35
)
)
)
);
I need to merge and center day titles (Thursday, Friday...) and merge with number of cells on the right. The number of merged cells equals to count($days[$day]['meals']).
The goal looks like this:
I use creating table from array $PHPexcelsheet->from_array($a); for table data. If it could be used for the header too, would be nice, but not necessary.
Finally I got to the solution. Doesn't seem so pretty, as I supposed, and also doesn*t work with more than 26 cols (which I don't need), but works.
$i = 0;
$c = 4;
$alphabet = range('A', 'Z');
while ($i < count($ceny_jidlo)) {
$den = $ceny_jidlo[$i];
$s = $alphabet[$c];
$sheet->setCellValue("{$s}1", $den['short']);
$co = $c;
$c = $c + count($den['opts']) - 1;
$e = $alphabet[$c];
for ($j = $co; $j <= $c; $j++)
colstyle($shit, $alphabet[$j], $eRow, 10);
$sheet->mergeCells("{$s}1:{$e}1");
$c++;
$i++;
}

how to iterate front and back in php foreach array?

I want to achieve this
foreach($spacecount as $x => $x_value) {
if($spacecount[$x+1] < $spacecount[$x+2] ) {
echo $spacecount[$x];
}
}
like we can do it in for loop, but i also want to use its key when needed. how can I perform it ?
The array looks like
Array ( [ Tables] => 5
[Home] => 0
[ Wallet] => 5
[Designer] => 0
)
it contains whitespaces in the key text
If there's no guarantee that your array is numerically indexed, you can do this:
$keys = array_keys($spacecount);
$values = array_values($spacecount);
for ($i = 0;$i < count($spacecount)-2;$i++) {
//If you need the key you can use $keys[$i]
if ($values[$i+1] < $values[$i+2]) {
echo $values[$i+1];
}
}

Unset an array value by having array of keys, which leads to it

I have an array which looks pretty much like this:
$array = [
0 => [
'b' => [
'classname1' => 'data1',
'classname2' => 'data2' // This one must go away
],
'classname3' => 'data3',
1 => [ ... ]
],
'a' => [ ... ],
'classnameN' => 'dataN'
];
This array can have any keys (numeric or string) and can be any levels deep. The question is how to unset part of it by having an array, which values are leading to some data in the first array?
For example using $definer = [0,'b','classname2']; we must delete commented part of an array.
I have a solution on how to find, what I need to delete, but I've realised, that I don't know how to travel back and assign new value to initial array:
$array_traveler = $array;
for($i = 0; $i < count($definer) - 1; $i++) {
$array_traveler = $array_traveler[$definer[$i]];
}
unset($array_traveler[$definer[count($definer) - 1]]);
Use "pointer"
$array_traveler = &$array;
for($i = 0; $i < count($definer) - 1; $i++) {
$array_traveler = &$array_traveler[$definer[$i]];
}
unset($array_traveler[$definer[count($definer) - 1]]);

How do I retrieve a random value in multidimensional associative array?

I have an array which contains information on posts I have made.
$DexArray = array(
array(
'url' => "http://i.imgur.com/ObXLdd6C.jpg",
'headline' => "Dronningens Nytårstale",
'subline' => "Tallene bag talen og årets spilforslag",
'href' => "nytaarstale.php",
'postedby' => "kris",
'postedurl' => "https://www.facebook.com/dataanalyticsdk",
'dato' => "21. december, 2014"
),
array(
'url' => "http://i.imgur.com/sxddhOe.jpg",
'headline' => "Endless Jewelry",
'subline' => "Are there really endless possibilities?",
'href' => "endless.php",
'postedby' => "Nikolaj Thulstrup",
'postedurl' => "kris",
'dato' => "10. december, 2014"
),
It is stored in a multidimensional associate array. I am trying to retrieve a random 'href' value in the array and store it as a variable.
I have tried using the array_rand function but it doesn't seem to work.
$k = array_rand($DexArray);
$v = $array[$k]['href'];
I get an error message saying: undefined variable: array in this line "$v = $array[$k]['href'];"
Do you have a solution for this?
It should be
$k = array_rand($DexArray);
$v = $DexArray[$k]['href'];
Here's a working debug :) link
There was a lingering , in your thingy. And $array was never defined in the first place, so that's what the error was telling you about.
Execute the code it will return the random value from the multidimensional php array.
<?php
$filter_field = array();
$original_items = array(
array(1, 'stuff1', 'info1', 'response1', 'info1', 'response1'), array(2, 'stuff2', 'info2', 'response2', 'info2', 'response2'), array(3, 'stuff3', 'info3', 'response3', 'info3', 'response3'), array(4, 'stuff4', 'info4', 'response4', 'info4', 'response4'));
for ($x = 0; $x < sizeof($original_items); $x++) {
array_push($filter_field, $original_items[$x][0]);
}
shuffle($filter_field);
echo "<br/><br/><br/>";
for ($x = 0; $x < sizeof($original_items); $x++) {
$k = $filter_field[$x];
for ($y = 0; $y < 5; $y++) {
echo $original_items[$k-1][$y];
}
echo "<br/><br/>";
}
?>
Here is another solution that will return the index of the random array.
$var = array(
array("a", "one"),
array("b", "two"),
array("c", "three"),
array("d", "four"),
array("e", "five"),
array("f", "six"),
array("g", "seven")
);
// array_rand returns the INDEX to the randomly
// chosen value, use that to access the array.
$finalVar = $var[array_rand($var)];
print_r($finalVar);

Categories