php - Merge 2 values in multidimensional array
Get the solution ↓↓↓After previously had exploded the data, there is a portion I need to rebuild/merge again. period in [category-X] index [1] with its value [2] should be merged and positioned in index [1].
Finally , the rest of index in each category should be moved up one step, since otherwise index [2] would be left blank.
My code:
$array = [
'category-1' => [
'data_first',
'period',
'0',
'data_last',
],
'category-2' => [
'data_first',
'period',
'2',
'data_last',
]
];
print_r($array);
Result
Array
(
[category-1] => Array
(
[0] => data_first
[1] => period
[2] => 0 // To be merged with period in index [1]
[3] => data_last
)
[category-2] => Array
(
[0] => data_first
[1] => period
[2] => 2 // To be merged with period in index [1]
[3] => data_last
)
)
Wanted Result
Array
(
[category-1] => Array
(
[0] => data_first
[1] => period0
[2] => data_last
)
[category-2] => Array
(
[0] => data_first
[1] => period2
[2] => data_last
)
)
Answer
Solution:
Extract the key values of array. Concatenate the both values (period, 0) and overwrite the index[1] with that result. Finally use unset to remove the index[2]
$keys = array_keys($array);
for ($i=0; $i < count($keys) ; $i++) {
$array[ $keys[$i] ][1] =
$array[ $keys[$i] ][1] . $array[ $keys[$i] ][2];
unset($array[ $keys[$i] ][2]);
}
print_r($array);
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: malformed utf-8 characters, possibly incorrectly encoded
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.