简体   繁体   中英

Extracting an array from another array in PHP

I have a question regarding array. I have an array shown below :

[1] => Arts and Humanities
[2] => Arts

I want this above array to be like :

[0]
    (
     [id] => 1 
     [field_name] => Arts and Humanities
  )
[1]
    (
     [id] => 2 
     [field_name] => Arts
  )

I didn t test this code, i wrote it on the row. but it can be something like this i think

$srcArray = array("Arts and Humanities", "arts");
$finalArray = array();

for ($i = 0; $i < count($srcArray); $i++)
 $tempArray = array("id" => $i + 1, "field_name" => srcArray[$i])
 array_push($finalArray, tempArray);
}

The best way to do this would simply be:

$array = [];

array_walk($oldArray, function ($value, $key) use (&$array) {
    $array[] = ['id' => $key, 'field_name' => $value];
});

This assumes $oldArray is [1] => Arts and Humanities [2] => Arts

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