简体   繁体   中英

Combine two arrays values with identical field count (Into an Object?)

I want to combine two arrays:

$fields = array("Field 1", "Field 2", "Field 3", "Field 4");

$values = array("Value 1", "Value 2", "Value 3", "Value 4");

What I need to obtain is:

$combined = array (
 [0] = array("Field 1", "Value 1"),
 [1] = array("Field 2", "Value 1"),
 [2] = array("Field 3", "Value 3"),
 [3] = array("Field 4", "Value 4")
)

Or if its possible:

$combined = array (
 [0] = array(['name'] => "Field 1", ['value'] => "Value 1"),
 [1] = array(['name'] => "Field 2", ['value'] => "Value 1"),
 [2] = array(['name'] => "Field 3", ['value'] => "Value 3"),
 [3] = array(['name'] => "Field 4", ['value'] => "Value 4")
)

I hope you can help me out with this,

Thanks to all!

$fields = array("Field 1", "Field 2", "Field 3", "Field 4");
$values = array("Value 1", "Value 2", "Value 3", "Value 4");

if (count($fields) == count($values))
{
    $newArray = array();
    for($i = 0; $i < count($fields); $i++)
    {
        $newArray[] = array('name' => $fields[$i], 'value' => $values[$i]);
    }

    // do what you want with your $newArray
}

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