Ian
Ian

Reputation: 151

Push an identical array key next to it

The problem is like this...

An existing array:

Array(
    [0] => array('sample 1', 'sample 2')
    [1] => array('cat', 'dog')
)

Another array:

Array(
    [0] => array('sample 3', 'sample 4')
)

What I want to happen to add it next to 0 key so it became:

Array(
    [0] => array('sample 1', 'sample 2')
    [1] => array('sample 3', 'sample 4')
    [2] => array('cat', 'dog')
)

How do you do this?

@maxhud I tried it but and the result is like this:

Array(
[0] => sample 1
[1] => sample 2
[2] => sample 3
[3] => sample 4
[4] => cat
[6] => dog
)

Here is my current current code snippet

$new_post_order = array();
foreach($the_query['posts'] as $the_post) {
$portfolio_reorder = '';
$portfolio_reorder = get_post_meta($the_post['ID'], 'portfolio_reorder', true); // Get the order on the db
if(empty($portfolio_reorder)) { // If its empty...
 $portfolio_reorder = 0; // Add default order                           
}
 array_splice($new_post_order, $portfolio_reorder, 0, $the_post);
}

echo '<pre>';
print_r( $new_post_order );
echo '</pre>';

Upvotes: 2

Views: 67

Answers (1)

Max Hudson
Max Hudson

Reputation: 10206

You accomplish this with array_splice:

http://php.net/manual/en/function.array-splice.php

Example:

$input = array("red", "green", "blue", "yellow");
array_splice($input, 3, 0, "purple");
// $input is now array("red", "green",
//          "blue", "purple", "yellow");

Give it a try yourself, and if you can't figure it out, make a comment and we'll help you out.

array_splice($new_post_order, $portfolio_reorder, 0, array($the_post));

Upvotes: 5

Related Questions