0

I have an array like this:

array(
    [cat] => news,
    [comments_count] => 2,
    [meta] => array(
        [first_meta] => 44,
        [second_meta] => 54,    
    )
)

The above code is an example of array that I have. Now I wanna make the above array clear like this:

array(
    [cat] => news,
    [comments_count] => 2,
    [first_meta] => 44,
    [second_meta] => 54,    
)

(means Delete -meta- but not it's indexes. I want to add indexes of meta to the first array)

3
  • Add your code also to see where is the problem. Commented Jan 17, 2018 at 16:28
  • can you be a bit more precise? do you want this as generic solution (do this for all arrays in your array), or just one time for the particular meta array? Commented Jan 17, 2018 at 16:30
  • @kaddath just for meta Commented Jan 18, 2018 at 11:33

2 Answers 2

4

Add the meta array to the array and then unset the meta array:

$array = $array + $array['meta'];
unset($array['meta']);
Sign up to request clarification or add additional context in comments.

Comments

1

You may use the below function if you have a multidimentional array and you can reuse it anywhere.

function array_flatten($array) { 
  if (!is_array($array)) { 
    return false; 
  } 
  $result = array(); 
  foreach ($array as $key => $value) { 
    if (is_array($value)) { 
      $result = array_merge($result, array_flatten($value)); 
    } else { 
      $result[$key] = $value; 
    } 
  } 
  return $result; 
}

$array = array(
'cat' => 'news',
'comments_count' => '2',
'meta' => array(
 'first_meta' => '44',
 'second_meta' => '54',    
                 )
);

var_dump(array_flatten($array));

The result will be

array(4) {
  ["cat"]=>
  string(4) "news"
  ["comments_count"]=>
  string(1) "2"
  ["first_meta"]=>
  string(2) "44"
  ["second_meta"]=>
  string(2) "54"
}

Otherwise if you just need to flatten meta array as in your question. array_merge() the meta array and unset meta it as below.

$result = array_merge($array, $array["meta"]);
unset($result["meta"]);
var_dump($result);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.