Fully flatten an array (#2956)

* Fully flatten an array

* Provide test coverage for CONCAT combined with INDEX/MATCH
This commit is contained in:
Jonathan Goode 2022-07-28 03:29:02 +01:00 committed by GitHub
parent b8456105dd
commit e460c82606
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 69 additions and 14 deletions

View File

@ -25,7 +25,7 @@ and this project adheres to [Semantic Versioning](https://semver.org).
### Fixed ### Fixed
- Nothing - Fully flatten an array [Issue #2955](https://github.com/PHPOffice/PhpSpreadsheet/issues/2955) [PR #2956](https://github.com/PHPOffice/PhpSpreadsheet/pull/2956)
## 1.24.1 - 2022-07-18 ## 1.24.1 - 2022-07-18

View File

@ -573,24 +573,20 @@ class Functions
return (array) $array; return (array) $array;
} }
$arrayValues = []; $flattened = [];
foreach ($array as $value) { $stack = array_values($array);
while ($stack) {
$value = array_shift($stack);
if (is_array($value)) { if (is_array($value)) {
foreach ($value as $val) { array_unshift($stack, ...array_values($value));
if (is_array($val)) {
foreach ($val as $v) {
$arrayValues[] = $v;
}
} else { } else {
$arrayValues[] = $val; $flattened[] = $value;
}
}
} else {
$arrayValues[] = $value;
} }
} }
return $arrayValues; return $flattened;
} }
/** /**

View File

@ -0,0 +1,34 @@
<?php
namespace PhpOffice\PhpSpreadsheetTests\Calculation;
use PhpOffice\PhpSpreadsheet\Calculation\Functions;
use PHPUnit\Framework\TestCase;
class ArrayTest extends TestCase
{
public function testMultiDimensionalArrayIsFlattened(): void
{
$array = [
0 => [
0 => [
32 => [
'B' => 'PHP',
],
],
],
1 => [
0 => [
32 => [
'C' => 'Spreadsheet',
],
],
],
];
$values = Functions::flattenArray($array);
self::assertIsNotArray($values[0]);
self::assertIsNotArray($values[1]);
}
}

View File

@ -2,6 +2,8 @@
namespace PhpOffice\PhpSpreadsheetTests\Calculation\Functions\TextData; namespace PhpOffice\PhpSpreadsheetTests\Calculation\Functions\TextData;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
class ConcatenateTest extends AllSetupTeardown class ConcatenateTest extends AllSetupTeardown
{ {
/** /**
@ -30,4 +32,27 @@ class ConcatenateTest extends AllSetupTeardown
{ {
return require 'tests/data/Calculation/TextData/CONCATENATE.php'; return require 'tests/data/Calculation/TextData/CONCATENATE.php';
} }
public function testConcatenateWithIndexMatch(): void
{
$spreadsheet = new Spreadsheet();
$sheet1 = $spreadsheet->getActiveSheet();
$sheet1->setTitle('Formula');
$sheet1->fromArray(
[
['Number', 'Formula'],
['52101293', '=CONCAT(INDEX(Lookup!$B$2, MATCH($A2, Lookup!$A$2, 0)))'],
]
);
$sheet2 = $spreadsheet->createSheet();
$sheet2->setTitle('Lookup');
$sheet2->fromArray(
[
['Lookup', 'Match'],
['52101293', 'PHP'],
]
);
self::assertSame('PHP', $sheet1->getCell('B2')->getCalculatedValue());
$spreadsheet->disconnectWorksheets();
}
} }