将键值对添加到现有数组或合并它们

时间:2016-05-20 08:34:07

标签: php arrays

我必须使用数组:

export PATH="/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin"

$门票:

$tickets = $db->loadObjectList();
$tickets_info = $details['ticket_info'];

$ tickets_info:

array (size=2)

0 => 
object(stdClass)[2924]
  public 'price' => string '100.000' 
  public 'name' => string 'Standard ticket'
1 => 
object(stdClass)[2972]
  public 'price' => string '150.000' 
  public 'name' => string 'Luxus ticket'

我正在尝试将98和50作为'available_tickets'添加到$ ticket数组中,如下所示:

array (size=2)
0 => string '98'
1 => string '50' 

我已经尝试过array_merge()并循环播放,但似乎没有什么对我有用。

3 个答案:

答案 0 :(得分:0)

我会选择以下解决方案:

foreach ( $tickets as $key => $ticket ) {
  if( array_key_exists( $key, $tickets_info ) ) {
    $tickets[$key]->available_tickets = $tickets_info[$key];
  } else {
    trigger_error('There is no equivalence to ticket #' . $key);
  }
}

答案 1 :(得分:0)

试试这个:

<?php 
$tickets = array( 0 =>array('price' =>  '100.000','name' => 'Standard ticket'),1 =>array( 'price' => '150.000','name' =>'Luxus ticket'));
$available = array(0=>98,1=>50);

foreach($tickets as $key =>$val)
{
    $tickets[$key]['available_tickets'] = $available[$key];
}
echo "<pre>"; print_r($tickets);
?>

这会给你:

Array
(
    [0] => Array
        (
            [price] => 100.000
            [name] => Standard ticket
            [available_tickets] => 98
        )

    [1] => Array
        (
            [price] => 150.000
            [name] => Luxus ticket
            [available_tickets] => 50
        )

<强> LIVE DEMO

答案 2 :(得分:0)

您可以使用数组映射执行此操作:

$tickets = array_map(function($a, $b) { $a->available_tickets = $b; return $a; }, $tickets, $tickets_info);

这会给你

Array
(
[0] => stdClass Object
    (
        [price] => "100.000"
        [name] => "Standard ticket"
        [tickets_available] => "98"
    )

[1] => stdClass Object
    (
        [price] => "150.000"
        [name] => "Deluxe ticket"
        [tickets_available] => "50"
    )

)