phparraysmultidimensional-array

Push two elements into the same level of an array


When user submits form the data is stored in array & serialized & stored in the database, when user again submit another form then that data is stored in array & previous serialized array is fetched from database & is unserialized.

Now I want both these array to be multi dimensional, here is what I've tried

$post = array();
$post[] = $co_name = test_input($_POST['co_name1']); 

this array is fetched from database $db = unserialize($db);

$db[] = $post;
print_r($db);

After Printing this is what i get

Array
(
    [0] => company_name
    [1] => country
    [2] => city
    [3] => state
    [4] => pincode
    [5] => 2008
    [6] => 01
    [7] => 2008
    [8] => Array
        (
            [0] => company_name
            [1] => country
            [2] => city
            [3] => state
            [4] => pincode
            [5] => 2008
            [6] => 01
            [7] => 2008
        ) 
)

Now my problem is second array is assigned to 8, how to perfectly create multi dimension array

My desired output is my array should like this

array(
    0=>array(
        0=>company_name
        1=>country
    ),
    1=>array(
        0=>company_name
        1=>location
    )
)

Solution

  • The following will give you a numerically indexed array with your POST data as one value and DB data as another value of a new array. If you var_dump / print_r() this, the output will look similar to your desired output:

    $newArray = array($post, $db);

    However; Your desired output shows a reduced number of keys for each result:

    ...(or did you only write these to make it easier to read?)

    If you do want just those two keys, consider using PHP's array_filter function which takes your combined array (above: $newArray) and a callback function as arguments. This allows you to manipulate any of the keys and values of the input array, to make the returned array look exactly as you like.