This question already has answers here:
Search for array row with specific column value and return another value from qualifying row
(3 answers)
Closed 2 months ago.
Good day
below is my ARRAY output
how do i load the price of a SKU by name?
i need the price of SKU PRODUCT1 for example which is 39.99
the array comes from a CSV which is converted to ARRAY
rough example
$SKU = "Product1";
$price = ['SKU']array; #somehow
echo $price;
Array output:
array(5) {
[0]=>
array(5) {
[0]=>
string(3) "SKU"
[1]=>
string(7) "Product"
[2]=>
string(5) "Price"
[3]=>
string(11) "Description"
[4]=>
string(5) "Image"
}
[1]=>
array(5) {
[0]=>
string(4) "PRODUCT1"
[1]=>
string(23) "Product Name stuff 1"
[2]=>
string(7) "$39.99 "
[3]=>
string(47) "desrption"
[4]=>
string(12) "product1.png"
}
[2]=>
array(5) {
[0]=>
string(4) "PRODUCT2"
[1]=>
string(13) "Product Name 2 stuff "
[2]=>
string(7) "$49.99 "
[3]=>
string(47) "product2descr"
[4]=>
string(11) "product2.png"
}
}
Good day
below is my ARRAY output
how do i load the price of a SKU by name?
i need the price of SKU PRODUCT1 for example which is 39.99 the array comes from a CSV which is converted to ARRAY
rough example
Assuming the array is named $a, loop through each row and look for the SKU in the first column:
foreach ( $a as $row ) {
if ( $row[0] == 'PRODUCT1' ) {
echo $row[2]; // Price
break;
}
}
Related
I have a dynamic list in which people can add categories and for each category they can add questions.
At the moment I store the title of the entire list in my database and the categories, both work but I can't figure out how to store the questions. I have them in an array so it shouldn't be that hard, still I can't get it to work.
This is my database structure:
templates:
id - template id
title - name of list (template)
id_company (company list belongs to, irrelevant for this question)
questioncat:
id - id of category
title - name of category
tid - template id that the category belongs to
questions:
id - question id
question - the actual question
catid - category id that the questions belong to
With the code I have at the moment I can add a template with categories linked to it. I do this with the code below:
$conn = new Connection;
$arr = $_POST['lijst'];
$companyid = $_POST['companyid'];
$store = [];
// pull off first arr element
$title = array_shift($arr);
// save title to store
$store['title'] = $title['name'];
// Insert template title and companyid
$inserttemplate = '
INSERT INTO templates (title, id_company) VALUES ("'.$conn->real_escape_string($title["value"]).'","'.$conn->real_escape_string($companyid).'")';
$inserttemplatecon = $conn->query($inserttemplate);
$lastinserted = $conn->inserted_id();
$currCat = '';
foreach($arr as $a) {
$val = $a['value'];
// handle category
if($a['name'] == 'category[]') {
// save cat name
$currCat = $val;
$insertcats = '
INSERT INTO questioncat (title, tid) VALUES ("'.$conn->real_escape_string($currCat).'", "'.$conn->real_escape_string($lastinserted).'")';
$insertcatscon = $conn->query($insertcats);
// init questions array
$store[$currCat] = [];
echo $store[$currCat];
}else {
// add question to question array
$store[$currCat][] = $val;
}
}
If I print the array $store when adding some example categories/questions this is an example result:
Array
(
[title] => lijsttitle
[Category 1] => Array
(
[0] => Question 1
[1] => Question 2
[2] => Question 3
)
[Category 2] => Array
(
[0] => Question 1
)
[Category 3] => Array
(
[0] => Question 1
)
[Category 4] => Array
(
[0] => Question 1
[1] => Question 2
)
)
I tried echoing echo $store[$currCat]; to see if I can show the questions but this is an array so it just shows Array, if I print it I just see Array().
How can I add the questions to my database with for each question the correct category id it belongs to?
var_dump of $arr as requested below:
array(11) {
[0]=>
array(2) {
["name"]=>
string(10) "category[]"
["value"]=>
string(10) "Category 1"
}
[1]=>
array(2) {
["name"]=>
string(10) "question[]"
["value"]=>
string(10) "Question 1"
}
[2]=>
array(2) {
["name"]=>
string(10) "question[]"
["value"]=>
string(10) "Question 2"
}
[3]=>
array(2) {
["name"]=>
string(10) "question[]"
["value"]=>
string(10) "Question 3"
}
[4]=>
array(2) {
["name"]=>
string(10) "category[]"
["value"]=>
string(10) "Category 2"
}
[5]=>
array(2) {
["name"]=>
string(10) "question[]"
["value"]=>
string(10) "Question 1"
}
[6]=>
array(2) {
["name"]=>
string(10) "category[]"
["value"]=>
string(10) "Category 3"
}
[7]=>
array(2) {
["name"]=>
string(10) "question[]"
["value"]=>
string(10) "Question 1"
}
[8]=>
array(2) {
["name"]=>
string(10) "category[]"
["value"]=>
string(10) "Category 4"
}
[9]=>
array(2) {
["name"]=>
string(10) "question[]"
["value"]=>
string(10) "Question 1"
}
[10]=>
array(2) {
["name"]=>
string(10) "question[]"
["value"]=>
string(10) "Question 2"
}
}
I think this should help:
foreach($arr as $ar){
foreach($ar as $key=>$val){
if(($key=="name")&&($val=="category[]"))
//insert into category table here and retrieve its id(category Id)
elseif(($key=="name")&&($val=="question[]"))
//insert into questions table with the retrieved category Id.
}
}
I have an array stored in a value: $data
The array's structure is as follows:
[0]=>
array(1447) {
[0]=>
array(3) {
[0]=>
string(10) "ga:country"
[1]=>
string(7) "ga:date"
[2]=>
string(11) "ga:sessions"
}
[1]=>
array(3) {
[0]=>
string(11) "Afghanistan"
[1]=>
string(8) "20151129"
[2]=>
string(1) "1"
}
[2]=>
array(3) {
[0]=>
string(7) "Algeria"
[1]=>
string(8) "20160413"
[2]=>
string(1) "1"
}
[3]=>
array(3) {
[0]=>
string(6) "Angola"
[1]=>
string(8) "20160511"
[2]=>
string(1) "1"
}
[4]=>
array(3) {
[0]=>
string(6) "Angola"
[1]=>
string(8) "20160524"
[2]=>
string(1) "5"
}
The array has 1400 entries and I need to make a top 5 of countries
[0]=>
string(11) "Afghanistan"
with highest values:
[2]=>
string(1) "1"
The top must also be of the entries from the last 30 days
I tried to achieve that like this:
function last30days($data)
{
foreach( $data->data[0] as $key => $item ){
$days = [];
for ($i = 1; $i <= 30
; $i++) {
$days[] = date("Y-m-d", strtotime(date('Y-m-01') . " -$i days"));
}
return $days;
}
But I don't know how to make the top 5 values of
[2]=>
string(1) "1"
. Also tell me please if I have approached the problem properly with that function. Thank you in advance.
So to make it clear I need to make top of [2] for every country...in this example Angola has the highest value
[2]=>
string(1) "5"
I can reach that value like this:
$data->data[0][4][2]
And I get 5
I have to loop through the array for the [2] value of every country and get the 5 highest values and the name of those 5 countries.
Below I've appended the $var_dump of an array that I've created through user-actions involving an HTML form.
I'm certainly willing to consider other strategies for achieving the final effect (and I'm not, to be honest, positive that it would not be better achieved via WordPress functions, since that's the environment this problem originates in), but the simplest answer would be to take the array described below, get rid of the "NULL" responses, then alphabetize ALL of the remaining sets by last name (which I originally put first since in an earlier, similar version of the same task it happened to make the final sort a snap).
The output will appear on a sign-in list at an event, with first column numbered, second column showing first name - last name with company underneath, a signature line, a line describing the "ticket type," and the ticket price.
SO, just to make it easy to picture:
No. FIRST/LAST/company SIGNATURE TICKET TYPE PRICE
(#) Amy Abrams, Carolco ......... Member $5
The natural way to do it, for me, was to produce an HTML table in which each variable, located by some kind of index, is output via PHP. I've had some versions that ALMOST worked, involving foreach loops at the very limits of my understanding of array manipulation.
I suspect that the person who can answer my question could write what I've tried in his or her sleep, but, just to give a flavor without dumping in a bunch more code... having gotten the below array in a variable called $meta, I could foreach through it foreach ($meta as $reservation), then print some of the variables, but not all of them, and not all in right order, with $reservation['first_name'][0], for example. I tried dropping an $i in place of the [0], and fooling around with other key/value/iterator combinations, but at this point I'm just iterating through my own internal array of ca. 999 wrong vs 1 right solutions.
I know this is a common type of question, but in poring through the threads here, I have yet to find a version like this one directly answered.
array(8) {
[0]=>
array(5) {
["last_name"]=>
NULL
["first_name"]=>
NULL
["price"]=>
NULL
["company"]=>
NULL
["ticket_type"]=>
NULL
}
[1]=>
array(5) {
["last_name"]=>
array(3) {
[0]=>
string(6) "Winger"
[1]=>
string(6) "Dinger"
[2]=>
string(7) "Stassen"
}
["first_name"]=>
array(3) {
[0]=>
string(5) "Debra"
[1]=>
string(3) "Hum"
[2]=>
string(6) "Harold"
}
["price"]=>
array(3) {
[0]=>
string(2) "10"
[1]=>
string(2) "10"
[2]=>
string(4) "6.35"
}
["company"]=>
array(3) {
[0]=>
string(14) "Post Data Test"
[1]=>
string(14) "Post Data Test"
[2]=>
string(14) "Post Data Test"
}
["ticket_type"]=>
array(3) {
[0]=>
string(16) "Shippable Ticket"
[1]=>
string(16) "Shippable Ticket"
[2]=>
string(14) "Special Ticket"
}
}
[2]=>
array(5) {
["last_name"]=>
NULL
["first_name"]=>
NULL
["price"]=>
NULL
["company"]=>
NULL
["ticket_type"]=>
NULL
}
[3]=>
array(5) {
["last_name"]=>
array(3) {
[0]=>
string(9) "Mightwork"
[1]=>
string(1) "u"
[2]=>
string(3) "why"
}
["first_name"]=>
array(3) {
[0]=>
string(9) "Bizarrely"
[1]=>
string(11) "whatsamatta"
[2]=>
string(8) "done no "
}
["price"]=>
array(3) {
[0]=>
string(1) "5"
[1]=>
string(4) "12.7"
[2]=>
string(4) "12.7"
}
["company"]=>
array(3) {
[0]=>
string(13) "Get Data Test"
[1]=>
string(13) "Get Data Test"
[2]=>
string(13) "Get Data Test"
}
["ticket_type"]=>
array(3) {
[0]=>
string(16) "Shippable Ticket"
[1]=>
string(14) "Special Ticket"
[2]=>
string(14) "Special Ticket"
}
}
[4]=>
array(5) {
["last_name"]=>
NULL
["first_name"]=>
NULL
["price"]=>
NULL
["company"]=>
NULL
["ticket_type"]=>
NULL
}
[5]=>
array(5) {
["last_name"]=>
array(2) {
[0]=>
string(7) "Marlatt"
[1]=>
string(7) "Stewart"
}
["first_name"]=>
array(2) {
[0]=>
string(4) "Jeff"
[1]=>
string(3) "Al "
}
["price"]=>
array(2) {
[0]=>
string(1) "0"
[1]=>
string(1) "0"
}
["company"]=>
array(2) {
[0]=>
string(23) "Jeff Marlatt Consulting"
[1]=>
string(23) "Jeff Marlatt Consulting"
}
["ticket_type"]=>
array(2) {
[0]=>
string(16) "testing defaults"
[1]=>
string(16) "testing defaults"
}
}
[6]=>
array(5) {
["last_name"]=>
NULL
["first_name"]=>
NULL
["price"]=>
NULL
["company"]=>
NULL
["ticket_type"]=>
NULL
}
[7]=>
array(5) {
["last_name"]=>
array(3) {
[0]=>
string(10) "Flintstone"
[1]=>
string(10) "Flintstone"
[2]=>
string(6) "Rubble"
}
["first_name"]=>
array(3) {
[0]=>
string(4) "Fred"
[1]=>
string(5) "Wilma"
[2]=>
string(5) "Betty"
}
["price"]=>
array(3) {
[0]=>
string(1) "0"
[1]=>
string(1) "0"
[2]=>
string(1) "0"
}
["company"]=>
array(3) {
[0]=>
string(23) "Jeff Marlatt Consulting"
[1]=>
string(23) "Jeff Marlatt Consulting"
[2]=>
string(23) "Jeff Marlatt Consulting"
}
["ticket_type"]=>
array(3) {
[0]=>
string(6) "MEMBER"
[1]=>
string(6) "MEMBER"
[2]=>
string(6) "MEMBER"
}
}
}
So firstly you have built your array in a very strange way. If all you want to do is output all the different guests it would be better to create a new element in your array for each guest, that way you could sort them and iterate them with ease. However as you have asked the question I will give you a solution...
To be able to sort your array we need to take your array and turn it into the array I described above. This array will look something like this...
array(
[0] => array(
[last_name] => 'blah',
[first_name] => 'blah',
[company] => 'blah',
[ticket_type] => 'blah',
[price] => 'blah',
),
[1] => array(
[last_name] => 'blah',
[first_name] => 'blah',
[company] => 'blah',
[ticket_type] => 'blah',
[price] => 'blah',
),
etc...
);
Then you can use the PHP function usort() to sort your multidimensional array by the value of the subarrays. Here's my solution...
//This function is used by usort() to sort the guests array by last name
//UPDATE: this function is now case insensitive and sorts on first name secondarily
function sort_by_last_name( $a, $b ) {
//Convert values to lowercase to make sorting case insensitive
$a_firstname = strtolower( $a['first_name'] );
$a_lastname = strtolower( $a['last_name'] );
$b_firstname = strtolower( $b['first_name'] );
$b_lastname = strtolower( $b['last_name'] );
//If the last names are the same sort by first name
if( $a_lastname == $b_lastname ) {
return strcmp( $a_firstname, $b_firstname );
}
return strcmp( $a_lastname, $b_lastname );
}
//This function returns a nicely formatted array of
//reservations sorted alphabetically by last name
function sort_reservations( $reservations ) {
//If reservations is empty get outta there
if( !$reservations || !is_array( $reservations ) ) { return false; }
//Create an empty array to store the formatted data
$guests = array();
//Loop through reservations
foreach ( $reservations as $res ) {
//If the reservation is empty skip onto the next one
if( !$res['last_name'] ) { continue; }
//See how many people are in the reservation
$count = count( $res['last_name'] );
//iterate through reservation n number of times
for( $i = 0; $i <= $count - 1; $i++ ) {
//Add reservations to the nsorted guests array
$guests[] = array(
'last_name' => $res['last_name'][$i],
'first_name' => $res['first_name'][$i],
'price' => $res['price'][$i],
'company' => $res['company'][$i],
'ticket_type' => $res['ticket_type'][$i]
);
}
}
//sort gusts by last name alphabetically
usort( $guests, 'sort_by_last_name' );
//Return our nicely formatted and sorted array
return $guests;
}
Now for example your unformatted array of reservations is stored in a variable $reservations you can sort it by using...
$guests = sort_reservations( $reservations );
Then you build your table in html and for each table row you can iterate over this array printing out a new guest to every row. like this....
<?php $guests = sort_reservations( $reservations ); ?>
<table>
<thead>
<tr>
<th class="firstname">First Name</th>
<th class="lastname">Last Name</th>
<th class="company">Company</th>
<th class="tickettype">Ticket Type</th>
<th class="price">Price</th>
</tr>
</thead>
<tbody>
<?php foreach( $guests as $guest ) { ?>
<tr>
<td class="firstname"><?php echo $guest['first_name']; ?></td>
<td class="lastname"><?php echo $guest['last_name']; ?></td>
<td class="company"><?php echo $guest['company']; ?></td>
<td class="tickettype"><?php echo $guest['ticket_type']; ?></td>
<td class="price">£<?php echo round( $guest['price'], 2 ); ?></td>
</tr>
<?php } ?>
</tbody>
</table>
And bob's your uncle, you've got a table of guests sorted alphabetically by their surnames.
Hope that helps
Dan
I try to update bigger array with some info from smaller array with same number of elements. Bigger array is generated every 24 hours but the smaller is generated every 4 hours but sometimes in smaller array there few elements less, so I want to delete these elements from bigger array but how I can do that?
Here is a first element of smaller array:
array(5) {
["category_id"]=>
string(1) "8"
["product_url"]=>
string(58) "http://example.net/?id=1752"
["price_bgn"]=>
float(142.8)
["price_eur"]=>
float(72.99)
["quantity"]=>
int(5)
}
Here is a first element of bigger array:
array(23) {
["product_id"]=>
string(4) "1752"
["product_sku"]=>
string(7) "SKU1752"
["category_id"]=>
string(1) "8"
["product_url"]=>
string(58) "http://example.net/?id=1752"
["additional_images"]=>
array(4) {
[0]=>
string(64) "http://example.net/vario.jpg"
[1]=>
string(73) "http://example.net/duraflex_logo1.jpg"
[2]=>
string(67) "http://example.net/YKK-logo.jpg"
[3]=>
string(67) "http://example.net/Air-mesh.jpg"
}
["variants"]=>
array(4) {
[0]=>
string(1) "1"
[1]=>
string(1) "2"
[2]=>
string(1) "3"
[3]=>
string(1) "4"
}
["related_products"]=>
array(4) {
[0]=>
array(2) {
["product_id"]=>
string(2) "18"
["product_sku"]=>
string(5) "SKU18"
}
[1]=>
array(2) {
["product_id"]=>
string(3) "248"
["product_sku"]=>
string(6) "SKU248"
}
[2]=>
array(2) {
["product_id"]=>
string(4) "1755"
["product_sku"]=>
string(7) "SKU1755"
}
[3]=>
array(2) {
["product_id"]=>
string(4) "1833"
["product_sku"]=>
string(7) "SKU1833"
}
}
["manufacturer_id"]=>
string(1) "1"
["quantity"]=>
int(5)
["metadescription_bg"]=>
string(233) ""
["detaileddescription_bg"]=>
string(5342) ""
["metadescription_en"]=>
string(159) ""
["metakeywords_en"]=>
string(38) ""
["name_en"]=>
string(38) ""
["price_eur"]=>
float(72.99)
["shortdescription_en"]=>
string(138) ""
["detaileddescription_en"]=>
string(2485) ""
["images_url"]=>
string(51) "http://example.net/?idpics=3948"
["images"]=>
array(4) {
[0]=>
string(50) "http://example.net/pic6129.jpg"
[1]=>
string(50) "http://example.net/pic6164.jpg"
[2]=>
string(50) "http://example.net/pic6165.jpg"
[3]=>
string(50) "http://example.net/pic5745.jpg"
}
}
So if I match product urls I update prices. But how to remove element from bigger array if there is no matched url in smaller array? This is the code for update:
foreach($this->productLinks as $product) {
foreach($this->productLinksOld as $k => $productOld) {
if($product['product_url'] == $productOld['product_url']) {
$this->productLinksOld[$k]['price_bgn'] = $product['price_bgn'];
$this->productLinksOld[$k]['price_eur'] = $product['price_eur'];
$this->productLinksOld[$k]['quantity'] = $product['quantity'];
}
}
}
cheers,
George!
I make a little check for this but I don't know is this the best way to do this. This is the code:
$links = unserialize(file_get_contents($this->_tempProductLinksFile));
$links[] = array(
'category_id' => 8,
'product_url' => 'http://www.example.net/?id=1752123',
'price_bgn' => 1.2,
'price_eur' => 0.6,
'quantity' => 15,
);
$products = unserialize(file_get_contents($this->_tempFullProductInfoFile));
echo count($links).' | '.count($products).'<br />';
foreach($links as $l) {
$ll[] = $l['product_url'];
}
foreach($products as $p) {
$pp[] = $p['product_url'];
}
foreach($products as $k => $pm) {
if(!in_array($pm['product_url'], $ll)) {
echo 'This key doesn\'t exists in small array '.$k.'<br />';
}
}
foreach($links as $k => $lm) {
if(!in_array($lm['product_url'], $pp)) {
echo 'This key doesn\'t exists in big array '.$k.'<br />';
}
}
First 1 get cached content for small array as links and for big array as products. Then I make new sub array to links to check case if in small array is a product without whole info in big array. After all I make a count for 2 arrays and the result is:
1501 | 1503
Then I get only product URLs in other arrays to check for each product url in other array and the result is:
This key doesn't exists in small array 44
This key doesn't exists in small array 313
This key doesn't exists in small array 685
This key doesn't exists in big array 1500
Which means that last record in links (created manually) not exists in big array and 3 other urls from products array doesn't exists in small array. Also run time of this code is ~200ms on my old home machine which is good enough for me :)
If any one can give me a better solution I'll be very grateful :)
cheers, George!
I have two arrays something like this
1) array(3) { [0]=> string(3) "max" [1]=> string(3) "min" [2]=> string(3) "med" }
2) array(4) { [0]=> string(3) "max" [1]=> string(3) "min" [2]=> string(4) "other" [3]=> string(3) "med" }
now i want to merge and delete the double entries of the two arrays, important thing is here to keep the order of the first array in the final array (max,min,med -> from first array, and then all others from second array)
the two arrays have different lengths array(3) and array(4)
$myfinalarray = (array_unique(array_merge($arr_first, $arr_last)));
the problem is the order is lost
result:
array(4) { [0]=> string(3) "max" [1]=> string(3) "min" [2]=> string(4) "other" [3]=> string(3) "med" }
what i need is this
array(4) { [0]=> string(3) "max" [1]=> string(3) "min" [2]=> string(3) "med" [3]=> string(4) "other" }
You should erase the double entries from 2nd array first:
$array_last = array_diff($arr_last, $arr_first);
and then
$myfinalarray = (array_unique(array_merge($arr_first, $arr_last)));
Order is not lost, but if you want to sort array in alphabetical order use sort function
$myfinalarray=sort($myfinalarray);
Check the below code,
<?php
$arr1=array(0 => "max",1 => "min",2 => "med");
$arr3=array(0 => "max",1 => "min",2 => "other",3 =>"med");
$myfinalarray = (array_unique(array_merge($arr1, $arr3)));
print_r($myfinalarray);
?>
the output willbe like,
Array
(
[0] => max
[1] => min
[2] => med
[5] => other
)
check here