将基于索引的数组转换为基于键的关联数组

时间:2013-08-14 06:44:01

标签: php arrays

我有这个数组:

Array (
    [0] => Rolex  (more)
    [1] => WG Submariner dial (only)
    [2] => 116619
    [3] => MINT
    [4] =>   
    [5] =>   
    [6] =>   
    [7] =>   
    [8] => WTB: Want To Buy
    [9] => Aug 7, 2013, 7:00 AM
    [10] => EUR 1,000 (in USD)
    [11] => EUR  *(estimate)
    [12] =>
)

我试图将它转换为像这样的关联数组:

Array (
    [brand] => Rolex  (more)
    [Series] => WG Submariner dial (only)
    [Model] => 116619
    [Condition] => MINT
    [Box] =>   
    [Papers] =>   
    [Year] =>   
    [Case Size] =>   
    [Status] => WTB: Want To Buy
    [Listed] => Aug 7, 2013, 7:00 AM
    [Asking Price] => EUR 1,000 (in USD)
    [Retail Price] => EUR  *(estimate)
    [Payment Info] =>
)

我正在考虑创建另一个数组,然后遍历它以分配名称密钥

除此之外的任何建议?

2 个答案:

答案 0 :(得分:3)

您可能需要查看array_combine

你仍然需要两个数组,但你不必循环来创建关联数组。

所以你有

$indexedArray = array( 'Rolex (more)', 'WG Submariner dial (only)', '116619' /* etc */ );
$keys = array('Brand', 'Series', 'Model', /* etc */);

$associativeArray = array_combine($keys, $indexedArray);

答案 1 :(得分:0)

这就是我所做的:

$params = array('brand'=>'brand','series'=>'series','model'=>'model','condition'=>'condition','box'=>'box','papers'=>'papers','year'=>'year','case size'=>'case size','status'=>'status','listed'=>'listed','asking price'=>'asking price','retail price'=>'retail price','payment info'=>'payment info');

Array (
    [0] => Rolex  (more)
    [1] => WG Submariner dial (only)
    [2] => 116619
    [3] => MINT
    [4] =>   
    [5] =>   
    [6] =>   
    [7] =>   
    [8] => WTB: Want To Buy
    [9] => Aug 7, 2013, 7:00 AM
    [10] => EUR 1,000 (in USD)
    [11] => EUR  *(estimate)
    [12] =>
)

$final_arr = array_combine($params,$post_meta);
            print_r($final_arr);

Array ( [brand] => Rolex  (more) [series] => WG Submariner dial (only) [model] => 116619 [condition] => MINT [box] =>   [papers] =>   [year] =>   [case size] =>   [status] => WTB: Want To Buy [listed] => Aug 7, 2013, 7:00 AM [asking price] => EUR 1,000 (in USD) [retail price] => EUR  *(estimate) [payment info] =>   )