Getting data from an object array - php

I have an array
Array (
[bla123] => Array
(
[0] => 2
[1] => 3
[2] => 2
[3] => 2
[4] => 2
[5] => 2
[6] => 2
[7] => 2
[8] => 2
)
[12xye] => Array
(
[0] => 4
[1] => 3
[2] => 3
[3] => 2
[4] => 2
[5] => 4
[6] => 2
[7] => 2
[8] => 2
)
)
How can i access this array in php and also get the number of 1,2,3.. etc from it in php.
The logic is to get the rating of a products. the data is fetched from the database completely and then sorted using php.
for eg:
product1
one star:1
two star:3
three star:2
etc...
somewhat like a star system in flipkart, amazons etc..

use the below code:
<?php
$mainArrDat = array('bla123'=>array('Your_Array_Data_Here'),'12xye'=>('Your_Array_Data_Here'));
foreach( $mainArrDat as $mainArr )
{
foreach($mainArr as $nowArr)
{
//you can access the data that you require from $nowArr
}
}
?>

Related

Get value multidimensional array and combine product group

I have created a multidimensional array using a csv file.
I get the following array:
Array
(
[0] => Array
(
[0] => Product
[1] => Price
[2] => Quantity
[3] => Date
)
[1] => Array
(
[0] => Teddybear
[1] => 3.789,33
[2] => 2
[3] => 2018-08-14
)
[2] => Array
(
[0] => Teddybear
[1] => 2.702,17
[2] => 1
[3] => 2018-02-17
)
[3] => Array
(
[0] => Table
[1] => 2.932,29
[2] => 5
[3] => 2018-10-09
)
[4] => Array
(
[0] => Lamp
[1] => 671,70
[2] => 3
[3] => 2018-12-11
)
[5] => Array
(
[0] => Teddybear
[1] => 481,21
[2] => 3
[3] => 2018-03-24
)
[6] => Array
(
[0] => Table
[1] => 456,52
[2] => 3
[3] => 2018-05-14
)
[7] => Array
(
[0] => Chair
[1] => 2.960,20
[2] => 2
[3] => 2018-06-20
)
[8] =>
)
I need to create a json file, but before that, I need to count al products and turnover per month
I'm a novice / junior PHP developer and I'm more specialized in WordPress, so forgive me for my bad code and/or bad practices. I'm here to learn.
I really don't know how to select for example all the Teddybears. I know I could do $csv[1][1]; to select turnover for the first Tedybear.
ok here there should be everything you need, I did 3 functions that you can chain together to get what you need, like in the example
$data=[
["Product","Price","Quantity","Date"], // <-- if you want to remove the header remove all the lines with this symbol *
["Teddybear",3789.33,2,"2018-08-14"],
["Teddybear",2702.17,1,"2018-02-17"],
["Table",2932.29,5,"2018-10-09"],
["Lamp",671.70,3,"2018-12-11"],
["Teddybear",481.21,3,"2018-03-24"],
["Table",45.52,3,"2018-05-14"],
["Chair",2960.20,2,"2018-06-20"]
];
function WhereFromColum($data,$colum,$equal){
$ret=[];
array_push($ret,$data[0]); // *
$colum = is_numeric($colum)?$colum:array_search($colum,$data[0]);
for($i=1/* 0 if you remove the header to data*/;$i!=count($data);$i++)
if ($data[$i][$colum]==$equal)
array_push($ret,$data[$i]);
return $ret;
}
function CountFromColum($data,$colum){
$ret=0;
$colum = is_numeric($colum)?$colum:array_search($colum,$data[0]);
for($i=1/* 0 if you remove the header to data*/;$i!=count($data);$i++)
$ret+=$data[$i][$colum];
return $ret;
}
function WhereFromColumData($data,$colum,$min,$max){
$contractDateBegin = new DateTime($min);
$contractDateEnd = new DateTime($max);
$ret=[];
array_push($ret,$data[0]); // *
$colum = is_numeric($colum)?$colum:array_search($colum,$data[0]);
for($i=1/* 0 if you remove the header to data*/;$i!=count($data);$i++){
$paymentDate = new DateTime($data[$i][$colum]);
if ($paymentDate->getTimestamp() > $contractDateBegin->getTimestamp() &&
$paymentDate->getTimestamp() < $contractDateEnd->getTimestamp())
array_push($ret,$data[$i]);
}
return $ret;
}
var_dump(WhereFromColum($data,"Product","Teddybear")); // get all Teddybear's Product
var_dump(CountFromColum($data,"Quantity")); // get all Quantity
var_dump(CountFromColum(WhereFromColum($data,"Product","Teddybear"),"Quantity")); // get all Quantity of Teddybear's Product
var_dump(WhereFromColumData($data,"Date","2018-08-01","2018-12-01")); // get all between 2018-08-01 and 2018-12-01
var_dump(WhereFromColumData(WhereFromColum($data,"Product","Teddybear"),"Date","2018-08-01","2018-12-01")); // get all Teddybear's Product between 2018-08-01 and 2018-12-01
usually I don't usually write code but explain how to do it but in your case it was too complex so please kindly read the three functions carefully and try to understand how they work, ps if you want to improve your skils in php I suggest you play a with these functions and modify them to fit what you need best. when you understand how they work you can also create another one with the same logic of nesting that allows you to make much more advanced filters.

PHP - Converting Array to group duplicates together - phpspreadsheet

I have a csv uploader i'm creating to push to an order api. Using phpSpreadsheets toArray method, i have an array like so:
Array
(
[0] => Array
(
[0] => product_sku
[1] => product_qty
[2] => shipping_name
[3] => shipping_address1
[4] => shipping_address2
[5] => shipping_city
[6] => shipping_county
[7] => shipping_postcode
[8] => shipping_type
[9] => customer_id
)
[1] => Array
(
[0] => test_sku_1
[1] => 3
[2] => Bruce Wayne
[3] => The Manor
[4] => Near Arkahm Asylumn
[5] => Gotham
[6] => Greater Gothan
[7] => B17MAN
[8] => 1
[9] => 14994333
)
[2] => Array
(
[0] => test_sku_2
[1] => 2
[2] => Bruce Wayne
[3] => The Manor
[4] => Near Arkahm Asylumn
[5] => Gotham
[6] => Greater Gothan
[7] => B17MAN
[8] => 1
[9] => 14994333
)
[3] => Array
(
[0] => test_sku_3
[1] => 7
[2] => Bruce Wayne
[3] => The Manor
[4] => Near Arkahm Asylumn
[5] => Gotham
[6] => Greater Gothan
[7] => L17MA2
[8] => 1
[9] => 14994333
)
)
Each order will be on a new line, however if a customer orders two different items, i need to group them together using their postcode. As such i was aiming to rearange into this format:
[orders] => Array(
Array(
[shipping_name] => "Bruce wayne",
[customer_id] => 14994333,
[address] => Array(
[shipping_address1] => "The Manor",
[shipping_address2] => "Near Arham Asylumn",
[shipping_city] => "Gotham",
[shipping_county] => "Greater Gotham",
[shipping_postcode] => "B17MAN",
)
[products] => Array(
Array(
[sku] => "test_sku_1",
[quantity] => 3
),
Array(
[sku] => "test_sku_2",
[quantity] => "2"
)
)
)
)
Once of the first problems i encountered was trying to match the postcodes. I managed to get a count using:
$getDuplicates = array_count_values(array_map(function($duplicates) {
return $duplicates[7]; //Where 7 is the postcode
}, $rows));
This worked in counting what i needed correctly. However from there i'm hitting a brick wall. If i'm counting the duplicates, i need it to also make a note of the rows it's already gone through so they aren't pushed incorrectly into the new array i want to make.
Pseudo it should be:
for each rows as row{
if row isn't set to be ignored{
for each count of this postcode{
array_push the product sku and qty
mark these rows as rows to be ignored
}
}
}
Can anyone help me with this?
So, long story short, i've been so caught up in this i completely missed the obvious. To solve this, i took the original array from phpspreadsheet and did an array_multisort:
foreach ($rows as $key => $row) {
$postcodes[$key] = $row[7]; //the postcode key
}
array_multisort($postcodes, SORT_DESC, $rows;
I then just worked my way through the array and if the postcode changed, i'd create a new array, otherwise i'd just push straight into the correct array for the products.
I feel really stupid i didn't think of this before. Thank you to #apokryfos for trying to help!

PHP Working with an array to find ranges and missing numbers

I have an array that looks like this:
[0] => Array
(
[1] => 5
[2] => 4
[3] => 3
[5] => 1
[7] => 1
[8] => 2
[9] => 3
[10] => 4
[11] => 5
)
[1] => Array
(
[1] => 6
[2] => 5
[4] => 3
[5] => 2
[6] => 1
[8] => 3
[9] => 4
[10] => 5
[11] => 6
)
[2] => Array
(
[1] => 7
[2] => 6
[3] => 5
[4] => 4
[5] => 3
[6] => 2
[7] => 3
[8] => 4
[11] => 7
)
I have an order of operations I'm trying to go through and I really don't know where to go from here. Any suggestions would be of great help.
First I give my class the number of items I want to return. For example here we'll use 4.
I want to loop through and find the item in the array that has the lowest value.
I want to look at the keys to the items around (it included) and be sure they're not missing a number if they are..reject it..
In this example the first one you would come to would be:
[5] => 1
Now looking around it you see that the keys are missing some numbers. So no combination of 4 will get that to match any 4 in the proper order.
[1] => 5
[2] => 4
[3] => 3
[5] => 1 //this one
[7] => 1
[8] => 2
[9] => 3
In this situation I want it to move onto the next case.
[7] => 1
Notice this one will work due to the keys being 7,8,9,10.
[7] => 1
[8] => 2
[9] => 3
[10] => 4
This is what I would like returned first..but I don't even know how to begin to get there.
Further more there are situations like this..Say for example there are no 1's at all in the dataset..and only this lone 2 in the last one.
[0] => Array
(
[1] => 5
[2] => 4
[3] => 3
[5] => 3
[7] => 3
[8] => 3
[9] => 3
[10] => 4
[11] => 5
)
[1] => Array
(
[1] => 6
[2] => 5
[4] => 3
[5] => 3
[6] => 3
[8] => 3
[9] => 4
[10] => 5
[11] => 6
)
[2] => Array
(
[1] => 7
[2] => 6
[5] => 3
[6] => 2 // this one
[7] => 3
[8] => 4
[11] => 7
)
The following wont work:
[6] => 2 // this one
[7] => 3
[8] => 4
[11] => 7
but this one will:
[5] => 3
[6] => 2 // this one
[7] => 3
[8] => 4
I have no idea on how to approach this.. If someone could offer some advice it would be GREATLY appreciated. Thanks so much in advance.
The following assumes your data is in an array called $data. I'll describe it in steps, then pull it all together as a function.
Step 1 find the min value:
$minValue=min($data);
Step 2 loop through the array looking for all values that are that value:
foreach($data as $index => $value){
if($value == $minValue){
// $index is a candidate!
}
}
Step 3 Check if $valuesToReturn entries exist after index:
$success=true;
for($i=1;$i<=$valuesToReturn;$i++){
if(!array_key_exists($index + $i,$data)){
// Candidate failed.
$success=false;
break;
}
}
Step 4 If the candidate was successful, return it.
if($success){
return $index;
}
Putting that all together, we get this:
function findSuitableIndex($data,$valuesToReturn){
// Min:
$minValue=min($data);
foreach($data as $index => $value){
if($value == $minValue){
// $index is a candidate!
// test if index is actually suitable:
$success=true;
for($i=1;$i<=$valuesToReturn;$i++){
if(!array_key_exists($index + $i,$data)){
// Candidate failed.
$success=false;
break;
}
}
if($success){
return $index;
}
}
}
// If we fell down here, we failed to find any successful results.
return -1;
}
Working sample:
Code on eval.in
Here are some suggestions. Your exact implementation would depend on your particular situation.
To loop through each element in the array, you could use a foreach loop.
foreach ($arr[0] as $index => $value) {
// Here, $arr[0][$index] == $value;
}
To check if a key exists or not, you could use array_key_exists.
if ( !array_key_exists($index - 1, $arr[0]) ) {
// The previous index is missing in the array.
}
A simple (but inefficient) way to find a contiguous sequence of k indices with the smallest value at the first index would be to find the smallest element and check if the contiguous sequence exists; if not, find the next smallest element and recursively check until you have completed processing the largest element.
You could also try finding all contiguous sequences of at least length k and then selecting the sequence with the smallest value at the first index.
Hope this helps!

php function to split array into 3 parts with out leaving remainders

I have an simple array that I would like split into 3 random rows.
So far I am using the array chunk function which successful splits it into 3 rows, but because the array count is uneven, it spilts the array into 3 rows but leaves a remainder 2 values in a 4th row. See code below...
<?php
$my_bikes = array (
'bike-996.png',
'bike-adventure.png',
'bike-bandit.png',
'bike-blade.png',
'bike-classic-racer.png',
'bike-classic-rm.png',
'bike-custom.png',
'bike-dragster.png',
'bike-ducati-scrambler.png',
'bike-electric-concept.png',
'bike-flat-tracker.png',
'bike-goldwing.png',
'bike-gsx.png',
'bike-harley.png',
'bike-indian-vintage.png',
'bike-kiddimoto.png',
'bike-livewire.png',
'bike-lotus.png',
'bike-monkey-bike.png',
'bike-moto3.png',
'bike-mx.png',
'bike-rc.png',
'bike-rc213v.png',
'bike-roland-sands.png',
'bike-scooter.png',
'bike-speedway.png',
'bike-tron.png',
'bike-vespa.png',
'bike-vision.png',
);
shuffle($my_bikes);
// chunk my bike
$my_bikes = array_chunk($my_bikes, count($my_bikes) / 3);
?>
<?php foreach($my_bikes as $key => $my_bike_row) : ?>
<div class="row <?=$key % 2==0 ? 'left' : 'right' ?>">
<?php foreach($my_bike_row as $my_bike): ?>
<img src="<?=get_path('images/bikes/' . $my_bike)?>" alt="">
<?php endforeach; ?>
</div>
<?php endforeach; ?>
<?=exit( '<pre>' . print_r( $my_bikes, true ));?>
See my current output below...
Array
(
[0] => Array
(
[0] => bike-roland-sands.png
[1] => bike-monkey-bike.png
[2] => bike-classic-rm.png
[3] => bike-classic-racer.png
[4] => bike-vespa.png
[5] => bike-rc213v.png
[6] => bike-flat-tracker.png
[7] => bike-dragster.png
[8] => bike-custom.png
)
[1] => Array
(
[0] => bike-speedway.png
[1] => bike-blade.png
[2] => bike-tron.png
[3] => bike-indian-vintage.png
[4] => bike-harley.png
[5] => bike-goldwing.png
[6] => bike-kiddimoto.png
[7] => bike-livewire.png
[8] => bike-moto3.png
)
[2] => Array
(
[0] => bike-adventure.png
[1] => bike-mx.png
[2] => bike-rc.png
[3] => bike-scooter.png
[4] => bike-996.png
[5] => bike-gsx.png
[6] => bike-ducati-scrambler.png
[7] => bike-lotus.png
[8] => bike-electric-concept.png
)
[3] => Array
(
[0] => bike-vision.png
[1] => bike-bandit.png
)
)
As you can see, I'm left with 4 rows.
My question is, what method is there with PHP where I can split the array into 3 rows, but if its an uneven number (as per my example) that the last the remainders are included the in the 3 rows, and not left remainding.
I don't wan't any duplicates ideally.
Thanks
Use array_chunk()
And calculate the size by rounding up the fraction(if any) to next highest integer value by ceil(count($my_bikes)/3)
So in this case - count($my_bikes)/3 => 26/3 => 8.66.
ceil(8.66) => 9
The chunk sizes will be 9, 9, 8
array_chunk($my_bikes, (ceil(count($my_bikes)/3)))
array_chunk($my_bikes,(count($my_bikes)/3)+1);

Sorting Multidimensional Array by Specific Key

EDIT: For anyone who might come across this post with a similar problem, It was solved by taking konforce's supplied answer and tweaking around a bit with the custom sorting function:
function cmp($a, $b) {
if ($a[5] == $b[5]) {
return ($a[3] < $b[3]) ? -1 :1;
}
return ($a[5] > $b[5]) ? -1 : 1;
}
Notice $a[5] == $b[5] does not return zero. It was changed to check who has the most losses and then sort it in ASC order. I'm sure you can even keep going and add another if-statement in there in-case they have the same losses.
Lastly, all you do is usort($ARRAY, "cmp"); and finito!!!
Original Post
My apologies for coming up with yet another MD Array sorting question but I'm just not getting it. I've searched aplenty
for a solution and although many sites have provided what seemed like a logical answer I still have not been able to figure it out.
My problem is since I'm still learning its been rather difficult for me to grasp the concept of using usort with a custom comparing
function. Atleast, thats what I have seen the most when others have tried to sort MD Arrays.
I'm working on a small project to sharpen up on my php skills. Its a very basic tournament standings script that holds a team's information within an array. I would like to sort the array by most points($array[X][X][5]).
So the array looks something like this:
Array (
[0] => Array (
[0] => Array (
[0] => cooller
[1] => 6
[2] => 6
[3] => 0
[4] => 0
[5] => 18
)
)
[1] => Array (
[0] => Array (
[0] => strenx
[1] => 9
[2] => 5
[3] => 1
[4] => 3
[5] => 18
)
)
[2] => Array (
[0] => Array (
[0] => rapha
[1] => 10
[2] => 8
[3] => 1
[4] => 1
[5] => 25
)
) [3] => Array (
[0] => Array (
[0] => ronald reagan
[1] => 5
[2] => 4
[3] => 0
[4] => 1
[5] => 13
)
)
)
I would like to sort it by most points(cell #5), so it would look like this after sorting:
Array (
[0] => Array (
[0] => Array (
[0] => rapha
[1] => 10
[2] => 8
[3] => 1
[4] => 1
[5] => 25
)
)
[1] => Array (
[0] => Array (
[0] => cooller
[1] => 6
[2] => 6
[3] => 0
[4] => 0
[5] => 18
)
)
[2] => Array (
[0] => Array (
[0] => strenx
[1] => 9
[2] => 5
[3] => 1
[4] => 3
[5] => 18
)
)
[3] => Array (
[0] => Array (
[0] => ronald reagan
[1] => 5
[2] => 4
[3] => 0
[4] => 1
[5] => 13
)
)
)
The player with 25 points would be at the top, followed by 18, 18, and lastly 13. Sorry for my earlier post, was having difficulty wording my question correctly. Thanks in advanced!
I think you want something like this:
usort($standings, function($a, $b) { return $b[0][5] - $a[0][5]; });
Or prior to PHP 5.3:
function cmp($a, $b) { return $b[0][5] - $a[0][5]; }
usort($standings, 'cmp');
When using usort, the $a and $b parameters will be one "layer" into the supplied array. So in your case, an example of $a or $b will be:
[0] => Array (
[0] => cooller
[1] => 6
[2] => 6
[3] => 0
[4] => 0
[5] => 18
)
I'm not sure why you have an extra containing array there, but as you can see, you want to sort based on the [0][5] position.
usort($standings[0][0][5], 'cmp') won't work because the first parameter isn't an array to sort, it's just a single number, the points.

Categories