60

Hi out there in Stackland. I was wondering if there was either a function or an easy way to change an associative array into an indexed array.

To elaborate, I'm using the Zend framework, and I've got a point in my site where I take out a row of an SQL table as an associative array. I've passed it to javascript via an echoed in JSON. However, I've noticed that I can see the names of my database's columns in Firebug. Having outsiders know the names of your tables and columns is a big security no-no, so I'd like to change it from

SQLarray[user_id]
SQLarray[block_id]
SQLarray[b_price] etc.

to

SQLarray[0]
SQLarray[1]
SQLarray[2] etc.

Is there a good way to do this?

It would also work to be able to have a Zend_Table_Abstract->fetchAll() return a non-associative array, but I don't think that's possible. Thanks for your help!

4

4 回答 4

173

纯php可以吗?

$array = array_values($array);

资源

于 2009-06-30T18:40:06.353 回答
6

定义函数

function array_default_key($array) {
    $arrayTemp = array();
    $i = 0;
    foreach ($array as $key => $val) {
        $arrayTemp[$i] = $val;
        $i++;
    }
    return $arrayTemp;
}

将关联数组作为参数传递,它将转换为数组的默认索引。例如:我们Array('2014-04-30'=>43,'2014-04-29'=>41)在调用函数后数组将是Array(0=>43,1=>41).

于 2014-07-09T10:10:23.100 回答
1

对于多层阵列,我使用这个:


function getIndexedArray($array) {
        $arrayTemp = array();
        for ($i=0; $i < count($array); $i++) { 
            $keys = array_keys($array[$i]);
            $innerArrayTemp = array();
            for ($j=0; $j < count($keys); $j++) { 

                $innerArrayTemp[$j] = $array[$i][$keys[$j]];                
            }
            array_push($arrayTemp, $innerArrayTemp);
        }
        return $arrayTemp;
    }

它变成了这样:

(
    [0] => Array
        (
          [OEM] => SG
            [MODEL] => Watch Active2
            [TASK_ID] => 8
            [DEPT_ASSIGNED] => Purchashing  
        )
)

进入这个:

[0] => Array
        (
          [0] => SG
            [1] => Watch Active2
            [2] => 8
            [3] => Purchashing  
        )
于 2020-02-04T15:19:42.370 回答
0

如果您不想使用内置的 PHP 函数,可以使用这段简单的代码。

$input_array;           // This is your input array
$output_array = [];     // This is where your output will be stored.
foreach ($input_array as $k => $v){
    array_push($output_array, $v);
}
print_r($output_array);
于 2015-12-03T10:26:25.863 回答