How can i add key index for a multidimensional array.
The array is fetched from from file gets contens url.
The variable that holds the array is looking like this:
$data = array(array($number, $firstmane, $lastname, $street));
The output is looking like this:
Array
(
[0] => Array
(
[0] => 13564
[1] => Bill
[2] => Willson
[3] => St 4546
)
)
Array
(
[0] => Array
(
[0] => 13295
[1] => Ken
[2] => Jibs
[3] => St 4156
)
)
How can i add index key so the array will look like this:
Array
(
[0] => Array
(
[0] => 13564
[1] => Bill
[2] => Willson
[3] => St 4546
)
)
Array
(
[1] => Array
(
[0] => 13295
[1] => Ken
[2] => Jibs
[3] => St 4156
)
)
UPDATE
More Complete Code
foreach ($json_obj['items'] as $order) {
$ordrenr = $order['id'];
$fornavn= $order['billingPerson']['firstName'];
$etternavn= $order['billingPerson']['lastName'];
$adresse = $order['billingPerson']['street'];
$header = ['ID' => 'string',
'Firstname' => 'string',
'Lastname' => 'string',
'street' => 'string'
];
$rader = array(array($ordrenr, $fornavn, $etternavn, $adresse));
print_r( $rader );
$writer = new XLSXWriter();
$writer->setAuthor('USERNAME');
$writer->writeSheet($rader, 'RESULT', $header);
$writer->writeToFile("/media/files/filename.xlsx" );
}
CodePudding user response:
You are just assigning an array of the array to $data. so you will only get the last array value in $data.
Try with following code in loop. $data[] = array($number, $firstmane, $lastname, $street);
$a= array('13564','Bill','Willson','St 4546'); $b= array('13295','Ken','Jibs','St 4546');
$data[] = array($a);
$data[] = array($b);
print_r($data);
Hope this will work for you.
CodePudding user response:
Create a new array item using $arr[] = [1,2,3];
and also I have changed the loop to create the complete array before attempting to write it out to the spreadsheet.
foreach ($json_obj['items'] as $order) {
$ordrenr = $order['id'];
$fornavn= $order['billingPerson']['firstName'];
$etternavn= $order['billingPerson']['lastName'];
$adresse = $order['billingPerson']['street'];
$header = ['ID' => 'string',
'Firstname' => 'string',
'Lastname' => 'string',
'street' => 'string'
];
//$rader = array(array($ordrenr, $fornavn, $etternavn, $adresse));
$rader[] = [$ordrenr, $fornavn, $etternavn, $adresse];
}
print_r( $rader );
$writer = new XLSXWriter();
$writer->setAuthor('USERNAME');
$writer->writeSheet($rader, 'RESULT', $header);
$writer->writeToFile("/media/files/filename.xlsx" );