PHP
5
Вклад в тег
<?php
function getColors($item_colors, $result = []){
preg_match_all('/(\w+),|(\w+)\/(\w+)/', $item_colors, $colors);
foreach ($colors as $key => $value) {
if ($key === 0) continue;
array_push($result, ...$value);
}
return array_filter($result);
}
$item_colors = "Vario Base Unit with steel, large, black/orange";
echo implode(' ', getColors($item_colors));
//steel large black orange
var_dump(getColors($item_colors));
// array(4) {
// [0]=>
// string(5) "steel"
// [1]=>
// string(5) "large"
// [5]=>
// string(5) "black"
// [8]=>
// string(6) "orange"
// }
<?php
$item_colors = "Vario Base Unit with steel, large, black/orange";
$result = [];
foreach (explode(', ', str_replace('Vario Base Unit with ','', $item_colors)) as $color) {
$colors = explode('/', $color);
count($colors) === 2 ? array_push($result, ...$colors) : array_push($result, $color);
}
echo implode(' ', $result);
//steel large black orange
var_dump($result);
// array(4) {
// [0]=>
// string(5) "steel"
// [1]=>
// string(5) "large"
// [2]=>
// string(5) "black"
// [3]=>
// string(6) "orange"
// }
<?php
$item_colors = "Vario Base Unit with steel, large, black/orange";
$result = eval('return '.str_replace(['Vario Base Unit with ', '/', ', '], ['["',', ', '", "'], $item_colors).'"];');
echo implode(' ', $result);
//steel large black orange
var_dump($result);
// array(4) {
// [0]=>
// string(5) "steel"
// [1]=>
// string(5) "large"
// [2]=>
// string(5) "black"
// [3]=>
// string(6) "orange"
// }
<?php
class KeysReplacer {
public $default = [
'id' => 'id',
'full_address' => 'adress',
'floorall' => 'floorall',
'build_year' => 'build_year',
];
public $services = [
'service_1' => [
'id' => 'internal_id',
'full_address' => 'locality',
'floorall' => 'floorall',
'build_year' => 'build_date'
],
'service_2' => [
'id' => 'ид',
'full_address' => 'полный_адрес',
'floorall' => 'этажность',
'build_year' => 'год_постройки'
],
];
public function __invoke($item, $from = null)
{
$result = [];
foreach($item as $key => $value){
$result[$from && isset($this->services[$from][$key])
? $this->services[$from][$key]
: $this->default[$key]] = $value;
}
return json_encode($result, JSON_UNESCAPED_UNICODE);
}
}
function getItem(){
return [
'id' => 1,
'full_address' => 'г. Москва',
'floorall' => 18,
'build_year' => 1990
];
}
$item = getItem();
$responseNormalizer = new KeysReplacer;
$response_0 = $responseNormalizer($item);
$response_1 = $responseNormalizer($item, 'service_1');
$response_2 = $responseNormalizer($item, 'service_2');
var_dump($response_0); // string(68) "{"id":1,"adress":"г. Москва","floorall":18,"build_year":1990}"
var_dump($response_1); // string(79) "{"internal_id":1,"locality":"г. Москва","floorall":18,"build_date":1990}"
var_dump($response_2); // string(112) "{"ид":1,"полный_адрес":"г. Москва","этажность":18,"год_постройки":1990}"