PHP Array / Multidimensional / Dynamic Array - php

I have an array from an xml file as follows:
Array
(
[0] => 1280
[1] => 1281
[2] => 1282
)
I have a second array of numbers that should be linked to the above array.
For example
1280 links to 0001, 0002, 0003
1281 links to 5000
1282 links to 3001, 2424
What is the best approach to link/associate the values in these two arrays?
All the values above are dynamic from XML and can be different any at time.
I think what I need is something like:
Array
(
[1280] => Array
(
[0] => 0001
[1] => 0002
[2] => 0003
)
[1281] => Array
(
[0] => 5000
)
[1282] => Array
(
[0] => 3001
[1] => 2424
)
)
and then loop through each array by 1280, 1281, 1282.
all values are provided from an XML file. There's at least 1 but can be as many as 100.
1280, 1281, 1282 are fitness classes and they are associated to a fitness instructor. All values are unique.
I can get the following:
1280, 0001
1280, 0002
1280, 0003
1281, 3000
etc.
Any suggestions?
Thanks.
UPDATE:
I am able to get the values in one array as such:
Array
(
[0] => 1280|0001
[1] => 1280|0002
[2] => 1280|0003
[3] => 1281|5000
[4] => 1282|3001
[5] => 1282|2424
)

Assuming that the values in arrays are integers and by the example of code that you want to get, this should do the trick.
$array1 = array(1280, 1281, 1282);
$array2 = array(array(1, 2, 3), array(5000), array(3001, 2424));
$result = array();
for ($i = 0; $i < $array1.size(); $i++) {
$result[$array1[$i]] = $array2[$i];
}

Related

Assign key number to php array objects

My code
$str = array(fgets($da, 1024));
print_r($str);
I'm trying to create an array in php from a dynamic output , but i noticed the keys in all object are [0], i need to assign a diferent key number to each object, how can i do that ?
Looks weird to me that all keys are 0, im trying to figure but nothing helps me.
Result :
Array
(
[0] =>
)
Array
(
[0] => 200
)
Array
(
[0] => 819105 rs fs
)
Array
(
[0] => 300 tert
)
Array
(
[0] => THO
)
Array
(
[0] => 91362
)
Array
(
[0] =>
)
Array
(
[0] => 06-20-21 6:56 PM
)
Array
(
[0] =>
)
Array
(
[0] =>
Array
(
[0] => 3 Cat 20 4.82 0.0 7.4 30
)
Array
(
[0] => 4 Dogs 19 26.2 0.8 7.1 62
)
Array
(
[0] =>
)
Thanks
If the input is reliable, you can split on whitespace for example:
$str = fgets($da, 1024);
$a = explode(" ", $str);
print_r($a);
array_merge with the spread (...) operator would work.
$str = array(fgets($da, 1024));
$str = array_merge(...$str);
All of the keys appear to be zero because you are wrapping each line from the file in its own array, so each array has one element at index zero.
If you define a buffer outside of your read loop, and add each line to it, each line will have its own index.
$da = fopen('test.txt', 'r');
// Define a buffer for the output
$data = [];
while (($str = fgets($da)) !== false)
{
// Add our line to the buffer
$data[] = $str;
}
fclose($da);
print_r($data);
output:
Array
(
[0] => 200
[1] => 819105 rs fs
[2] => 300 tert
[3] => THO
[4] => 91362
[5] => 06-20-21 6:56 PM
[6] => 3 Cat 20 4.82 0.0 7.4 30
[7] => 4 Dogs 19 26.2 0.8 7.1 62
)
But it looks like you may have some sort of header information in the first 6 lines of the file, maybe info from an HTTP request? Then lines that are somehow delimited, maybe by tab, but then the text got munged somewhere on the way into the SO post?
You can use a combination of fgets and fgetcsv to pull the data from the file and organize it into associative arrays.
Input:
200
819105 rs fs
300 tert
THO
91362
06-20-21 6:56 PM
3 Cat 20 4.82 0.0 7.4 30
4 Dogs 19 26.2 0.8 7.1 62
5 Wombat 20 4.20 0.0 6.9 30
6 Hedgehogs 19 26.2 0.8 7.1 62
$da = fopen('test.txt', 'r');
// Define a buffer for the output
$data = [];
// Define the fields in the header, each header line needs an entry
$headerDef = [
'status',
'transfer_stats',
'what_is_this',
'something_else',
'content_length',
'timestamp'
];
// Define the columns in the data rows, each column needs an entry
$columnDef = [
'id',
'type',
'count',
'average_weight',
'tax',
'food_weight_percent_per_day',
'fluffiness'
];
// Define an array to hold the header contents
$headerData = [];
// For each line in the header definition, extract a line from the file
while (!empty($headerDef) && $str = fgets($da, 1024))
{
$currValue = trim($str);
// Pull the next field from the front of the array
$currHeaderField = array_shift($headerDef);
// Set the entry in the header data array
$headerData[$currHeaderField] = $currValue;
}
while ($row = fgetcsv($da, 1024, "\t"))
{
// Create a new associative array by combining the column names and the row data
$data[] = array_combine($columnDef, $row);
}
fclose($da);
print_r($headerData);
print_r($data);
output:
Array
(
[status] => 200
[transfer_stats] => 819105 rs fs
[what_is_this] => 300 tert
[something_else] => THO
[content_length] => 91362
[timestamp] => 06-20-21 6:56 PM
)
Array
(
[0] => Array
(
[id] => 3
[type] => Cat
[count] => 20
[average_weight] => 4.82
[tax] => 0.0
[food_weight_percent_per_day] => 7.4
[fluffiness] => 30
)
[1] => Array
(
[id] => 4
[type] => Dogs
[count] => 19
[average_weight] => 26.2
[tax] => 0.8
[food_weight_percent_per_day] => 7.1
[fluffiness] => 62
)
[2] => Array
(
[id] => 5
[type] => Wombat
[count] => 20
[average_weight] => 4.20
[tax] => 0.0
[food_weight_percent_per_day] => 6.9
[fluffiness] => 30
)
[3] => Array
(
[id] => 6
[type] => Hedgehogs
[count] => 19
[average_weight] => 26.2
[tax] => 0.8
[food_weight_percent_per_day] => 7.1
[fluffiness] => 62
)
)
Of course the field names are just made up, I have no idea what your actual data is. And I'm assuming that the data rows are delimited with tabs, that may not be the case. But you should be able to use this as a starting point.
PS. It could be that the HTTP data at the top of the file is included by mistake, perhaps from a curl request? You could change that with the CURLOPT_HEADER option and curl_setopt

Moving array element to beginning of array?

If I have an array like the one below how would I go about moving key [2] and its associated value to the beginning of the array ? (making it key [0] and increasing the other keys by 1)
Current:
[0] => Array
(
[name] => Vanilla Coke cans 355ml x 24
)
[1] => Array
(
[name] => Big Red Soda x 24
)
[2] => Array
(
[name] => Reeses White PB Cups - 24 CT
)
Desired outcome:
[0] => Array
(
[name] => Reeses White PB Cups - 24 CT
)
[1] => Array
(
[name] => Vanilla Coke cans 355ml x 24
)
[2] => Array
(
[name] => Big Red Soda x 24
)
EDIT
To clarify I do will always want to move an element to the begining of the array but it wont necessarily be the last element it can sometimes be the 3rd 4th e.c.t. it varies each time.
array_splice removes (and optionally replaces / inserts) values from an array returning an array with the removed items. In conjunction with the simple array_unshift function the job could be done.
$arr = [1,2,3,4,5];
function array_move_item_as_first(array $array, int $idx) : array
{
array_unshift( $array, array_splice($array, $idx, 1)[0] );
return $array;
}
print_r(array_move_item_as_first($arr, 2));
output:
Array
(
[0] => 3
[1] => 1
[2] => 2
[3] => 4
[4] => 5
)
Why don't you use array_unshift and array_pop together?
array_unshift($someArray, array_pop($someArray));
array_pop removes the last element, and array_shift prepends the entry to the array.

PHP Average Values in Multiple Arrays to 1 Array

I have an array full of numbers and I can easily get the average of one array with.
if(count($averageprice)) {
$averageprice= array_filter($averageprice);
$averageprice= array_sum($averageprice)/count($averageprice);
}
But say I have 4 arrays all with prices. They are all in the right order and contain the same amount of values. How can I create a single array that keeps the order of each value but averages it between all arrays?
Thanks!
Edit for better example:
$array1 =array(10,15,20);
$array2 =array(14,13,22);
$array3 =array(12,18,26);
I want a new array that averages all the values in the array into one array. Note the amount of arrays isn't always the same per each time. However no matter how many arrays it is, they will always have the same amount of values in it. (Sometimes 4, sometimes 8, etc)
FIRST WAY: arrays in different variables
$arr0 = [0,10,2];
$arr1 = [0,20,4];
$arr2 = [0,30,6];
Note: array_filter will remove the 0's... For example: the average
of [0, 10, 2] will be 6 (i.e.: (10 + 2) / 2) and NOT (0+10+2)/3 = 4. Is
this really what you mean? Do you want to discard 0's before averaging?
$arr0 = array_filter($arr0);
$arr1 = array_filter($arr1);
$arr2 = array_filter($arr2);
print_r($arr0); // (just to point out again the previous comment)
Array
(
[1] => 10
[2] => 2
)
THIS IS THE IMPORTANT LINE:
$averages = array_map(function($a){return array_sum($a)/count($a);}, [$arr0, $arr1, $arr2]);
print_r($averages)
Array
(
[0] => 6
[1] => 12
[2] => 18
)
SECOND WAY: All the arrays inside a bigger array.
$arrs = [[0,10,2], [0,20,4], [0,30,6]];
$arrs = array_map(function($a){return array_filter($a);}, $arrs);
$result = array_map(function($a){return array_sum($a) / count($a);}, $arrs);
print_r($arrs);
Array
(
[0] => Array
(
[1] => 10
[2] => 2
)
[1] => Array
(
[1] => 20
[2] => 4
)
[2] => Array
(
[1] => 30
[2] => 6
)
)
print_r($result);
Array
(
[0] => 6
[1] => 12
[2] => 18
)

PHP array in array - DXF script

I found a php script to write DXF file based on coordinates of polygon. IT works on the test file with this code (for polygon):
$d->append(new DxfPolyLine(array('points'=>array(array(1, 1),
array(20, 10),
array(20, 20),
array(1, 15)),
'lineType'=>'DASHED',
// 'layer' => 'DXFWRITER',
'flag' => 0
//'width' => 1,
//'color'=>1
)
));
The DXF file result is like this:
VERTEX
8
0
6
DASHED
10
20.000
20
20.000
0
VERTEX
8
0
6
DASHED
10
1.000
20
15.000
0
A lot of vertex's inside a polyline.
Now I am trying to insert my own coordinates. I have the coordinates but how can I write an array in that array?
I have this: $g=array_merge($g,array(array($coord[$z]*3.527785, $coord[$z+1]*3.527785)));
With this code the result is:
Array ( [0] => Array ( [0] => -133.92170714209 [1] => -41.834100838885 ) [1] => Array ( [0] => -135.19600658422 [1] => -44.558002415365 ) [2] => Array ( [0] => -173.40700872797 [1] => -25.465001344078 ) [3] => Array ( [0] => -211.44500829533 [1] => -6.4740001788315 ) [4] => Array ( [0] => -209.93490817601 [1] => -3.255100166471 ) [5] =>
Array ( [0] => -190.0770099388 [1] => -13.202000524885 ) [6] => Array ( [0] => -171.92300716209 [1] => -22.296000898041 ) [7] => Array ( [0] => -172.13500940166 [1] => -22.749000947663 ) [8] => Array ( [0] => -171.12900859213 [1] => -23.251001225378 ) [9] => Array ( [0] => -152.49300807866 [1] => -32.559001622754 ) [10] => Array ( [0] => -133.92170714209 [1] => -41.834100838885 ) )
So far so good. It respects the format from example. But in the DXF file does write only 1 (from array number).
If I change the code in
$d->append(new DxfPolyLine(array('points'=>array($g[3]),
with array[3] - it does write the coordinates in DXF file. Is there a way to make php to read all arrays from an array? I've tried with foreach but it doesn't work. PHP gives an error for not closing the ).
The source code is here:
https://github.com/digitalfotografen/DXFwriter
With $g[3] I have the coordinates from array[3] in DXF file:
VERTEX
8
0
6
CONTINUOUS
10
-211.445
20
-6.474
0
If I put $g simple I have:
VERTEX
8
0
6
CONTINUOUS
10
1.000
20
1.000
30
1.000
40
1.000
50
1.000
60
1.000
70
1.000
I recreated the $g array based on your dump. Does this outputs the desired DXF file?
$g = [[-133.92170714209, -41.834100838885],
[-135.19600658422, -44.558002415365],
[-173.40700872797, -25.465001344078],
[-211.44500829533, -6.4740001788315],
[-209.93490817601, -3.255100166471 ],
[-190.0770099388 , -13.202000524885],
[-171.92300716209, -22.296000898041],
[-172.13500940166, -22.749000947663],
[-171.12900859213, -23.251001225378],
[-152.49300807866, -32.559001622754],
[-133.92170714209, -41.834100838885]
];
$d->append(new DxfPolyLine(['points' => $g]));
regarding building the array, you could do something like this:
for ($z = 0; $z < $numar; $z+=2) {
$g[] = [$coord[$z]*3.527785,$coord[$z+1]*3.527785];
}
Your formatting's a bit screwy, but looking at the dumped array-data I see a single array who's values are arrays, that have 2 float values each. Note that Array[0] and Array[10] have the same values which may or may not be a problem for the lib.
Also, what's with the asterisks in the $d->append... logic?
Is there a way to make php to read all arrays from an array?
Yes, but PHP will impose some restrictions depending on the nature of the keys and values. See http://php.net/manual/en/language.types.array.php for more specific info as to how PHP treats arrays.
I've tried with foreach but it doesn't work. PHP gives an error for not closing the ).
Can you post the failing code please? What you describe is simply a formatting / syntax error and nothing to do with the data itself.

PHP Array Slice understanding

I have the following array:
Array
Array (
[0] => Array (
...
)
[41] => Array (
[name] => London
[company] => nhyt6t
[top25_1] => 8.75912088
)
[42] => Array (
[name] => Manchester
[company] => gtr4rf
[top25_1] => 6.56758398
)
...
[75] => Array (
[name] => Leeds
[company] => de3wsd6
[top25_1] => 7.58675398
)
)
If my reading and understanding of http://www.php.net/manual/en/function.array-slice.php is correct, then the following should return just those within the array with an index of between 40 and 65.
$array = array_slice($array, 40, 65);
However, in practise, what this does is remove Indexes 0 through 39 but leaves everything else.
Can anyone explained where I am going wrong?
Just try with:
$array = array_slice($array, 40, 65 - 40);
So:
$array = array_slice($array, 40, 25);
We start slicing from 40 position and get 25 elements (ending on 40+25=65 position).
Array slice chooses an offset and length, not a begin offset and end offset. It starts at the begin offset and chooses the next length elements. If your array has continuous indices (0,1,2,3,4...), then it will slice from [offset -> offset + length)

Categories