Get specific key value pairs from associative array - php

I`m new to PHP and probably this one is basic question, but...I have an associative array (result of json_decode function). For example it looks like this:
$cars = array
(
array("brand"=>"Volvo", "price" => 10000, "type"=> 1),
array("brand"=>"Audi", "price" => 20000, "type"=> 2),
array("brand"=>"Ford", "price" => 30000, "type"=> 3),
array("brand"=>"Audi", "price" => 31000, "type"=> 3),
array("brand"=>"Ford", "price" => 32000, "type"=> 2),
array("brand"=>"Audi", "price" => 33000, "type"=> 2)
);
I need to loop $cars and get just brand and price as key value pair where brand is Audi because of a need to convert each to an object then.
Thanks!

Pretty simple. Use foreach to iterate through each car. If car brand name is 'Audi' then it will add it the entry it's on to an array.
<?php
$cars = array
(
array("brand"=>"Volvo", "price" => 10000, "type"=> 1),
array("brand"=>"Audi", "price" => 20000, "type"=> 2),
array("brand"=>"Ford", "price" => 30000, "type"=> 3),
array("brand"=>"Audi", "price" => 31000, "type"=> 3),
array("brand"=>"Ford", "price" => 32000, "type"=> 2),
array("brand"=>"Audi", "price" => 33000, "type"=> 2)
);
$audis = [];
foreach ($cars as $car) {
if ($car['brand'] == 'Audi') {
$audis[] = ['price' => $car['price'], 'type' => $car['type']];
}
}
foreach ($audis as $audi) {
print_r($audi);
}
This returns all Audi's
Array
(
[price] => 20000
[type] => 2
)
Array
(
[price] => 31000
[type] => 3
)
Array
(
[price] => 33000
[type] => 2
)
Link: https://eval.in/769607

Related

Refactor foreach with multilevel array

I'm currently returning results from a sql statement in an array like so:
$results = [];
foreach($promotionTool as $p){
$results[] = $p;
}
return $results;
Which my console shows in an object with this structure:
(2) [{…}, {…}]
0:
codeID: "41"
code: "123ABC"
rule_type: "Category"
attribute_type: "identifier"
attribute_title: "category number"
attribute_value: "234"
1:
codeID: "41"
code: "123ABC"
rule_type: "Category"
attribute_type: "amount"
attribute_title: "percent"
attribute_value: "25"
This is showing the data I expect but I'm a little bit lost on how to restructure this so that I can group on certain levels and finally return only an array of the attributes like so:
codeID
code
rule_type
array(
0:
attribute_type: "identifier"
attribute_title: "category number"
attribute_value: "234"
1:
attribute_type: "amount"
attribute_title: "percent"
attribute_value: "25"
)
How would I refactor my foreach to group at multiple levels in that way?
I guess this is what you are looking for:
<?php
$input = [
[
'codeID' => "41",
'code' => "123ABC",
'rule_type' => "Category",
'attribute_type' => "identifier",
'attribute_title' => "category number",
'attribute_value' => "234"
],
[
'codeID' => "41",
'code' => "123ABC",
'rule_type' => "Category",
'attribute_type' => "amount",
'attribute_title' => "percent",
'attribute_value' => "25"
]
];
$output = [];
array_walk($input, function ($e) use (&$output) {
$output[$e['codeID']][$e['code']][$e['rule_type']][] = [
'attribute_type' => $e['attribute_type'],
'attribute_title' => $e['attribute_title'],
'attribute_value' => $e['attribute_value']
];
});
print_r($output);
This could be a variant easier to read:
array_walk($input, function ($e) use (&$output) {
$codeID = &$e['codeID'];
$code = &$e['code'];
$rule_type = &$e['rule_type'];
$output[$codeID][$code][$rule_type][] = [
'attribute_type' => $e['attribute_type'],
'attribute_title' => $e['attribute_title'],
'attribute_value' => $e['attribute_value']
];
});
The output obviously is:
Array
(
[41] => Array
(
[123ABC] => Array
(
[Category] => Array
(
[0] => Array
(
[attribute_type] => identifier
[attribute_title] => category number
[attribute_value] => 234
)
[1] => Array
(
[attribute_type] => amount
[attribute_title] => percent
[attribute_value] => 25
)
)
)
)
)

How can I search an array for specific values?

I need some help with how I can search an array from a search box.
Lets say I search for the $ticker and write BTC
It will then print out:
The last known currency for BTC is 57
I only want it to print out $k3 values.
Appreciate if you could take your time and guide me in the right direction :)
<form method="POST" action="">
<input type="text" name="Searcharray" name="searcharray">
<input type="submit" value="Search" name="searcharray">
</form>
<?php
$ticker = array(
0 => "BTC",
1 => "ETH",
2 => "LTC",
3 => "XMR",
4 => "XRP"
);
$name = array(
0 => "Bitcoin",
1 => "Ethereum",
2 => "Litecoin",
3 => "Monero",
4 => "Ripple"
);
$k1 = array(
0 => 1,
1 => 2,
2 => 3,
3 => 4,
4 => 5
);
$k2 = array(
0 => 11,
1 => 12,
2 => 13,
3 => 14,
4 => 15
);
$k3 = array(
0 => 17,
1 => 27,
2 => 37,
3 => 47,
4 => 57
);
?>
array_search would help - http://php.net/manual/de/function.array-search.php
$index = array_search('BTC', $ticker);
$value = $k3[$index];
Why dont you make such a structure?:
$data = [
'BTC' => [
'name' => 'Bitcoin',
'k1' => 1,
'k2' => 11,
'k3' => 17
], ...
];
then it would be:
$value = $data['BTC']['k3'];
$index = array_search("BTC", $ticker);
if ($index !== FALSE) {
$currency = $k3[$index];
echo "The last known currency of BTC is $currency";
}
But things would be easier if you used a 2-dimensional associative array:
$data = [
"BTC" => ["name" => "Bitcoin", "k1" => 1, "k2" => 11, "k3" => 17],
"ETH" => ["name" => "Ethereum", "k1" => 2, "k2" => 12, "k3" => 27],
...
];
Then you can do:
if (isset($data["BTC"])) {
$currency = $data["BTC"]["k3"];
echo "The last known currency of BTC is $currency";
}

Multiply price and quantity of each row, then sum to calculate total

My code goes as:
<?php
$items = array(
array("SKU" => "a49w8dsa", "Title" => "Socks", "Description" => "Sports socks", "Price" => "1.50", "Quantity" => "4"),
array("SKU" => "ta8dla", "Title" => "T-shirt", "Description" => "ABC Brand undershirt", "Price" => "14.25", "Quantity" => "2"),
array("SKU" => "yusa982", "Title" => "Flip Flips", "Description" => "XYZ Brand Beach Flops", "Price" => "2.88", "Quantity" => "5"),
array("SKU" => "gnbaiue", "Title" => "Ball Cap", "Description" => "No Name", "Price" => "3.58", "Quantity" => "1"),
array("SKU" => "ythwq836", "Title" => "Frizbee", "Description" => "Whammo Frisbee Disc", "Price" => "2.47", "Quantity" => "2")
);
$final = array_shift($items);
foreach (array_column as $key => &$value){
$value += array_sum(array_row($Price . $Quantity));
}
unset($value);
var_dump($final);
I want to grab the price of each item, multiply it by the quantity in that array and add the sums to a variable, then print.
Get price of each item into an array, then finally sum it up using array_sum() -
$eachPrice = array();
foreach ($items as $key => $val) {
$eachPrice[] = $val['Price'] * $val['Quantity'];
}
$totalPrice = array_sum($eachPrice);
var_dump($totalPrice); // should be total price of all items

Array search, add and delete

I have the following table:
CREATE TABLE sample (id INT AUTO_INCREMENT PRIMARY KEY, entry_id INT NOT NULL, last_change timestamp);
INSERT INTO sample (entry_id) VALUES (1), (2), (3), (4);
My code does the following:
Receives POST input and compares the values to the table above.
If the the POST data has a value that does not exist in the entry_id column, then it will perform an INSERT statement.
If the table has a value in the entry_id column that does not exist in the POST data, then it will perform a DELETE statement
PHP Code:
<?php
// $_POST data:
$submittedEntries = array(1, 3, 4, 5, 6);
// $dbORM->getEntries()
$currentEntries = array(
array("id" => 100, "entry_id" => 1, "timestamp" => "2014-07-24 2:14:00"),
array("id" => 101, "entry_id" => 2, "timestamp" => "2014-07-24 2:14:00"),
array("id" => 102, "entry_id" => 3, "timestamp" => "2014-07-24 2:14:00"),
array("id" => 103, "entry_id" => 4, "timestamp" => "2014-07-24 2:14:00"),
)
$entriesToAdd = array();
$entriesToRemove = array();
// Find Entries to Add
// Loop through each entry submitted
foreach($submittedEntries as $entry_id) {
$exists = false;
// Loop through all Current Entries
foreach($currentEntries as $existingEntry) {
// Find matching IDs
if ($existingEntry["entry_id"] == $entry_id) {
$exists = true;
}
}
if ($exists == false) {
$entriesToAdd[] = $entry_id;
}
}
// Find Entries to Remove
// Loop through all Current Entries
foreach($currentEntries as $existingEntry) {
$remove = true;
// Loop through each entry submitted
foreach($submittedEntries as $entry_id) {
// Find matching IDs
if ($existingEntry["entry_id"] == $entry_id) {
$remove = false;
}
}
if ($remove == true) {
$entriesToRemove[] = $existingEntry["entry_id"];
}
}
// Add New Entries
foreach($entriesToAdd as $entry_id) {
$dbORM->addEntry($entry_id);
}
// Remove Entries
foreach($entriesToRemove as $entry_id) {
$dbORM->removeEntry($entry_id);
}
$entries = $dbORM->getEntries(); // SELECT * from sample;
print_r($entries);
/*
Expected Output:
array(
array("id" => 100, "entry_id" => 1, "timestamp" => "2014-07-24 2:14:00"),
array("id" => 102, "entry_id" => 3, "timestamp" => "2014-07-24 2:14:00"),
array("id" => 103, "entry_id" => 4, "timestamp" => "2014-07-24 2:14:00"),
array("id" => 104, "entry_id" => 5, "timestamp" => "2014-07-24 3:27:00"),
array("id" => 105, "entry_id" => 6, "timestamp" => "2014-07-24 3:27:00")
)
*/
Is there a better way to do this? I looked into all the php array functions and they do not seem to be able to deep search of multidimensional arrays.
If the table has to always be exactly like the POST, simplest way is to DELETE all rows and then INSERT all posts.
Another solution could be the use of unique key on entry_id...
This way you could really simply do 2 small queries:
$insert = "INSERT IGNORE INTO sample (entry_id)VALUES(".implode('),(',$submittedEntries).")";
$delete = "DELETE FROM sample WHERE entry_id NOT IN(".implode(',',$submittedEntries).")";
If you want to compair the two lists in PHP then you can use array_walk() to run through the db list and then use in_array() to see if it's in the submitted POST. You can then filter into two arrays.
<?php
$entriesToAdd = array();
$entriesToRemove = array();
$submittedEntries = array(1, 3, 4, 5, 6);
$currentEntries = array(
array("id" => 100, "entry_id" => 1),
array("id" => 101, "entry_id" => 2),
array("id" => 102, "entry_id" => 3),
array("id" => 103, "entry_id" => 4),
);
function AWS(&$item, $key) {
global $submittedEntries, $entriesToAdd, $entriesToRemove;
if(in_array($item["entry_id"], $submittedEntries))
{
array_push($entriesToAdd, $item);
}
else
{
array_push($entriesToRemove, $item);
}
}
array_walk( $currentEntries, 'AWS' );
echo "Add:";
print_r($entriesToAdd);
echo "Remove:";
print_r($entriesToRemove);
This outputs:
Add:Array
(
[0] => Array
(
[id] => 100
[entry_id] => 1
)
[1] => Array
(
[id] => 102
[entry_id] => 3
)
[2] => Array
(
[id] => 103
[entry_id] => 4
)
)
Remove:Array
(
[0] => Array
(
[id] => 101
[entry_id] => 2
)
)

Get repeated key => values in every array within a multiarray + other no repeated key = > values

i have this multi array "$marray wich has inside some array with some similar key = value and some not look like this :
$marray = array(
array("id" => "1", "be_pro" => 6, "name" => "a1", "service" => 4a),
array("id" => "2", "be_pro" => 6, "name" => "a1", "service" => 4d),
array("id" => "3", "be_pro" => 4, "name" => "a4", "service" => 3d),
array("id" => "4", "be_pro" => 4, "name" => "a4", "service" => 3s),
array("id" => "6", "be_pro" => 4, "name" => "a4", "service" => 34),
array("id" => "8", "be_pro" => 3, "name" => "a3", "service" => 4r),
array("id" => "8", "be_pro" => 3, "name" => "a3", "service" => 4d)
);
So i would like to get new arrays with "id", "be_pro" and "name" once then "service" plus "service" from next array till "be_pro" in the new array is different , so if is different put in the next array.
How should i do this?
what i need is print a multi array and within and array with every row with similar be_pro
This help me:
// first get all bepro_id and put in array
foreach($all_rows as $service){
$bepros[$service['bepro_id']]++;
}
//var_dump($bepros);
//Then for each be pro_id print every row , so print every service , then for be pro_id,id,name just print the first key "[0]" the array inside $new_array
foreach ($bepros as $key=>$bepro){
if(isset($new_bep)){
$x = 0 + $new_bep;
}else{
$x = 0;
}
$new_array[] = array_slice($all_rows,$x,$bepro);
// get where let before
$new_bep=$x + $bepro;
}

Categories