简体   繁体   中英

How to create an array within Array in php

Hi Guys Please help me in creating an array like below

array (
  array ( "5555776741" , "Don0454545" , "Draper" ),
  array ( "5551112239" , "betty777777" , "Smith" ),
  array ( "9999999999", "test", "name")
)

From an array $contacts which prints as below with print_r($contacts) as:

Array
(
[0] => Array
    (
        [phone_mobile] => +16046799329
        [first_name] => 
        [last_name] => test
    )

[1] => Array
    (
        [phone_mobile] => 7326751700
        [first_name] => Ralph
        [last_name] => OBrien
    )

[2] => Array
    (
        [phone_mobile] => 3204937568
        [first_name] => Chris
        [last_name] => Barth
    )

)

Im trying to achieve from the below code : but the value passed is not assigned from $contact to $record the Print_r($contact) prints empty arrays.

foreach ($contacts as $contact)
{
    $record =$contact;
}

You can do this, so you won't have to specify each array keys.

$data = [];
foreach ($contacts as $contact) {
    $data[] = array_values($contact);
}

The following isn't tested, but should work for you.

$data = [];
foreach ($contacts as $contact)
{
    $data[] = [ $contact['phone_mobile'], $contact['first_name'], $contact['last_name'] ];
}

You could also use array_values() within a Loop for that like so:

<?php
    $result = [];
    $arr    = [
            [
            'phone_mobile'  => '+16046799329',
            'first_name'    => '',
            'last_name'     => 'test'
            ],
            [
            'phone_mobile'  => '7326751700',
            'first_name'    => 'Ralph',
            'last_name'     => 'OBrien'
            ],
            [
            'phone_mobile'  => '3204937568',
            'first_name'    => 'Chris',
            'last_name'     => 'Barth'
            ],
    ];

    foreach($arr as $i=>$data){
        $result[]   = array_values($data);
    }
    var_dump($result);

In addition to directly iterating, you can also get the result you want by mapping array_values over your contacts array.

$record = array_map('array_values', $contacts);

It's basically the same thing as the foreach answer from Sam, just a bit more condensed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM