php数组转换而不是数字放名称

时间:2015-10-11 14:10:19

标签: php arrays

如何更改下面的数组--->

$data = Array
(
    [1] => Samsung GT-i9300 Galaxy S III 16GB
    [4] => Samsung GT-i9100 Galaxy S II
)

到这个--->

    $data = Array
        (
    [0] => Array
        (
            [name] => Samsung GT-N7100 Galaxy Note II 16GB
        )

    [1] => Array
        (
            [name] => Samsung GT-i9100 Galaxy S II
        )

4 个答案:

答案 0 :(得分:1)

我建议的唯一方法是转换你的数组:

var tbody = document.querySelector("#table tbody");
var trs = document.querySelectorAll("#table tbody tr");
tbody.appendChild(trs[0]);
tbody.appendChild(trs[1]);

所以现在你走过<table id="table"> <tbody> <tr><td>1</td></tr> <tr><td>2</td></tr> <tr><td>3</td></tr> <tr><td>4</td></tr> </tbody> </table>并抓住$data = array ( '1' => 'Samsung GT-i9300 Galaxy S III 16GB', '4' => 'Samsung GT-i9100 Galaxy S II' ); $newData = array(); foreach ($data as $key=>$val ) { $newData[$key]['name'] =$val; } 作为一个字段:

$newData

答案 1 :(得分:1)

如果您需要,请点击此处:

ModuleCriticalLevel

答案 2 :(得分:1)

$data = array(
    1 => 'Samsung GT-i9300 Galaxy S III 16GB',
    4 => 'Samsung GT-i9100 Galaxy S II'
);

$newData = array_map(function ($e) {
    return array('name' => $e);
}, array_values($data));

var_dump($newData);

答案 3 :(得分:1)

您也可以使用array_push,即:

$array =  array("Samsung GT-i9300 Galaxy S III 16GB", "Samsung GT-i9100 Galaxy S II");
$newarray = array();
foreach($array  as $model){
array_push($newarray, array('name' => $model) );
}
print_r($newarray);

<强>输出:

Array
(
    [0] => Array
        (
            [name] => Samsung GT-i9300 Galaxy S III 16GB
        )

    [1] => Array
        (
            [name] => Samsung GT-i9100 Galaxy S II
        )

)

<强>样本:

http://ideone.com/QTqAjr