PHP数组(看到xml)

时间:2018-01-20 09:34:04

标签: php arrays xml

我正在尝试从PHP数组中实现此输出。

<Timesheets>
  <Timesheet>
    <EmployeeID>5e493b2e-c3ed-4172-95b2-593438101f76</EmployeeID>
    <StartDate>2013-04-03</StartDate>
    <EndDate>2013-04-10</EndDate>
    <Status>Draft</Status>
    <TimesheetLines>
      <TimesheetLine>
        <EarningsRateID>0daff504-2d42-4243-bdac-24f2bae0ce7c</EarningsRateID>
        <NumberOfUnits>
          <NumberOfUnit>8.00</NumberOfUnit>
          <NumberOfUnit>8.00</NumberOfUnit>
          <NumberOfUnit>8.00</NumberOfUnit>
          <NumberOfUnit>8.00</NumberOfUnit>
          <NumberOfUnit>8.00</NumberOfUnit>
          <NumberOfUnit>0.00</NumberOfUnit>
          <NumberOfUnit>0.00</NumberOfUnit>
        </NumberOfUnits>
      </TimesheetLine>
    </TimesheetLines>
  </Timesheet>
</Timesheets> 

我的PHP代码是(只有数组)

        $new_timesheet = array();
        $new_timesheet['Timesheet'] = array();
        $new_timesheet['Timesheet']['EmployeeID'] = '8534e85a-e398-4041-99b1-cce51e7a8a02';
        $new_timesheet['Timesheet']['StartDate'] = "2018-01-22";
        $new_timesheet['Timesheet']['EndDate'] = "2018-01-28";
        $new_timesheet['Timesheet']['Status'] = "Draft";
        $new_timesheet['Timesheet']['Hours'] = "5.0";
        $new_timesheet['Timesheet']['TimesheetLines'] = array();
        $new_timesheet['Timesheet']['TimesheetLines']['TimesheetLine'] = array();
        $new_timesheet['Timesheet']['TimesheetLines']['TimesheetLine']['EarningsRateID'] = '0daff504-2d42-4243-bdac-24f2bae0ce7c';
        $new_timesheet['Timesheet']['TimesheetLines']['TimesheetLine']['NumberOfUnits'] = array();
        $new_timesheet['Timesheet']['TimesheetLines']['TimesheetLine']['NumberOfUnits'][]['NumberOfUnit'] = array('8.00');
        $new_timesheet['Timesheet']['TimesheetLines']['TimesheetLine']['NumberOfUnits'][]['NumberOfUnit'] = array('9.00');

但意外地我得到了这个输出

<Timesheets>
  <Timesheet>
    <EmployeeID>8534e85a-e398-4041-99b1-cce51e7a8a02</EmployeeID>
    <StartDate>2018-01-22</StartDate>
    <EndDate>2018-01-28</EndDate>
    <Status>Draft</Status>
    <Hours>5.0</Hours>
    <TimesheetLines>
      <TimesheetLine>
        <EarningsRateID>0daff504-2d42-4243-bdac-24f2bae0ce7c</EarningsRateID>
        <NumberOfUnits>
          <NumberOfUnit>8.00</NumberOfUnit>
        </NumberOfUnits>
        <NumberOfUnits>
          <NumberOfUnit>9.00</NumberOfUnit>
        </NumberOfUnits>
      </TimesheetLine>
    </TimesheetLines>
  </Timesheet>
</Timesheets>

你可以看到它正在重复“NumberOfUnits”标签,这是不正确的。 输出应该是第一个。 任何人都可以帮我吗?

1 个答案:

答案 0 :(得分:0)

根据您的要求,您有一个NumberOfUnits数组,其中有多个NumberOfUnit条目。

您可以通过以下方式分配NumberOfUnit数组来实现所需的结果

$new_timesheet['Timesheet']['TimesheetLines']['TimesheetLine']['NumberOfUnits']['NumberOfUnit'][] = '8.00';
$new_timesheet['Timesheet']['TimesheetLines']['TimesheetLine']['NumberOfUnits']['NumberOfUnit'][] = '9.00';