获取没有键名的PHP数组的值

时间:2019-06-16 02:39:03

标签: php

我需要从这样的数组中获取一个值:

array (size=1)
'row_3' => 
  array (size=1)
  'viagem' => 
    array (size=10)
      'veiculo_id' => string '1' (length=1)
      'motorista_id' => string '1' (length=1)
      'data' => string '2019-06-05' (length=10)
      'destino' => string 'A' (length=1)
      'vrUnit' => string '' (length=0)
      'horaSaida' => string '00:00:00' (length=8)
      'horaChegada' => string '00:00:00' (length=8)
      'kmInicial' => string '' (length=0)
      'kmFinal' => string '' (length=0)
      'autorizado' => string 'A' (length=1)

如果我使用$var = $_POST['data']['row_3']['viagem']['destino'];,这项工作。

但是键['row_3']并不固定,键可以是['row_5']['row_10']等。

所以,我的问题是如何使用类似$var = $_POST['data']??something??['viagem']['destino'];的代码来获取价值?

3 个答案:

答案 0 :(得分:2)

尝试:

$var = $_POST['data'][array_keys($_POST['data'])[0]]['viagem']['destino'];

答案 1 :(得分:1)

array_column或多层array_shift可能在这里工作,可能在那里或四个array_shift

array_shift(array_shift(array_shift($_POST)))['destino'];

答案 2 :(得分:1)

您只需要访问您所选择的深度的已知密钥,然后使用Private Sub OPCode() Dim sql As String = "SELECT * From totais Where data Between @StartDate And @EndDate;" Using dt As New DataTable Using cn As New OleDbConnection("Your connection string"), cmd As New OleDbCommand(sql, cn) cmd.Parameters.Add("@StartDate", OleDbType.Date).Value = DateTimePicker1.Value cmd.Parameters.Add("@EndDate", OleDbType.Date).Value = DateTimePicker2.Value cn.Open() dt.Load(cmd.ExecuteReader) End Using DataGridView1.DataSource = dt End Using End Sub 来获取动态密钥

代码:(Demo

key()

输出:

$_POST = [
    'data' => [
        'row_3' => [
            'viagem' => [
                'veiculo_id' => '1',
                'motorista_id' => '1',
                'data' => '2019-06-05',
                'destino' => 'A',
                'vrUnit' => '',
                'horaSaida' => '00:00:00',
            ]
        ]
    ]
];

echo $_POST['data']['row_3']['viagem']['destino'];
echo "\n---\n";
$rowKey = key($_POST['data']);  // no need to generate an entire temporary array of keys
echo $_POST['data'][$rowKey]['viagem']['destino'];