Array
(
[1] => dani : developer
[2] => john : not_developer
)
i want to split this array at ":" and create in each place another array.
expected output :
Array
(
[1] => array(
"name" => "dani",
"value" => "developer"
)
[2] => array(
"name" => "john",
"value" => "not_developer"
)
)
i have tried using explode(":", $attribute); but the explode wont work on array.
CodePudding user response:
Use array_map, with a custom callback, to map the original into what you want:
<?php
$original =[
'dani : developer',
'john : not_developer',
];
$converted = array_map(
function ($element) {
list($name, $value) = explode(':', $element);
return [
'name' => trim($name),
'value' => trim($value),
];
},
$original
);
var_dump($converted);
You can use this variation that uses array_map again to do the exploding and trimming together:
<?php
$original =[
'dani : developer',
'john : not_developer',
];
$converted = array_map(
function ($element) {
list($name, $value) = array_map(
'trim',
explode(':', $element)
);
return [
'name' => $name,
'value' => $value,
];
},
$original
);
var_dump($converted);
Or this variation that further uses a preset array of the desired output's sub-keynames, and array_combine:
<?php
$original =[
'dani : developer',
'john : not_developer',
];
$conversion_keys = ['name', 'value'];
$converted = array_map(
function ($element) use ($conversion_keys) {
return array_combine(
$conversion_keys,
array_map(
'trim',
explode(':', $element)
)
);
},
$original
);
var_dump($converted);
They all output your desired result of:
array(2) {
[0]=>
array(2) {
["name"]=>
string(4) "dani"
["value"]=>
string(9) "developer"
}
[1]=>
array(2) {
["name"]=>
string(4) "john"
["value"]=>
string(13) "not_developer"
}
}
CodePudding user response:
$attributes_array = array();
foreach( $hebrew_attributes_array as $attribute ){
$attribute_array = explode(":", $attribute);
$attributes_array[] = Array(
"attribute_name" => $attribute_array[0],
"attribute_value" => $attribute_array[1]
);
}
// $hebrew_string = explode(":", $hebrew_string);
return $attributes_array;
