如何重新格式化数组

时间:2016-09-07 14:33:25

标签: php

我有一个像

这样的索引的数组
$array = array(
    "first_name" => "test",
    "last_name" => "testsurename"
);

我需要将其转换为:

$array = array(
    "0" => array("first_name" => "test"),
    "1" => array("last_name" => "testsurename")
);

4 个答案:

答案 0 :(得分:3)

试试这个,

$array = array("first_name"=>"test","last_name"=>"testsurename");
$newarray = array();
foreach($array as $key=> $val)
{
    $newarray[][$key] = $val;
}
print_r($newarray);

输出

$array = array(
    "0" => array("first_name" => "test"),
    "1" => array("last_name" => "testsurename")
);

<强> DEMO

答案 1 :(得分:2)

另一种方法是使用array_walk,但基本上它都是一样的。

$array = array("first_name"=>"test","last_name"=>"testsurename");

$result = array();

array_walk($array, 
           function(&$item, $key, $target) { $target[] = array($key => $item); },
           &$result);

答案 2 :(得分:1)

你可以尝试

<?php
$array = array("first_name"=>"test","last_name"=>"testsurename");

$final_array = [];
foreach ($array as $key => $value) {
    array_push($final_array, [$key => $value]);
}

print_r($final_array);

输出

Array ( [0] => Array ( [first_name] => test ) [1] => Array ( [last_name] => testsurename ) )

答案 3 :(得分:1)

void CMyGridProperty::OnDrawValue(CDC* pDC, CRect rect)
{
    // pre-processing
    // ...

    CString strVal = FormatProperty();
    if(!strVal.IsEmpty())
    {
        strVal = _T("******");  // NOTE: replace the plain text with "******"
    }
    rect.DeflateRect(AFX_TEXT_MARGIN, 0);
    pDC->DrawText(strVal, rect, DT_LEFT | DT_SINGLELINE | DT_VCENTER | DT_NOPREFIX | DT_END_ELLIPSIS);

    // post-processing
    // ...
}

CWnd* CMyGridProperty::CreateInPlaceEdit(CRect rectEdit, BOOL& bDefaultFormat)
{
    // pre-processing
    // ...

    CEdit* pWndEdit = new CEdit;
    DWORD dwStyle = WS_VISIBLE | WS_CHILD | ES_AUTOHSCROLL | ES_PASSWORD;   // NOTE: add 'ES_PASSWORD' style here
    pWndEdit->Create(dwStyle, rectEdit, m_pWndList, AFX_PROPLIST_ID_INPLACE);

    // post-processing
    // ...

    return pWndEdit;
}