Reading/Accessing 2d/3d array - php

I did a query on a table that returned two columns of data with 5 rows. I stored these in an array but I can't figure out how to access the data. This is the result of the array:
/*
Array (
[0] => Array (
[contributions] => 99
[key_projects] => 4
)
[1] => Array (
[contributions] => 2
[key_projects] => 26
)
[2] => Array (
[contributions] => 1
[key_projects] => 26
)
[3] => Array (
[contributions] => 0
[key_projects] => 52
)
[4] => Array (
[contributions] => 0
[key_projects] => 53
)
)
*/
$result_array = array();
while ($row = mysqli_fetch_assoc($result)) {
$result_array[] = $row;
}
If I do echo $result_array[0][0] I get Array 0 echo'd.

echo $result_array[0]['contributions']; // displays: 99
echo $result_array[4]['key_projects']; // displays: 53

You are using fetch_assoc withc means your returned arrays will use the keys from your query
so you need to use those to access the data:
echo $result_array[0]['contributions'];
//or
foreach($result_array as $row){
echo "Contributions:".$row['cotributions'].", Key Projects".$row['key_projects']."\n";
}
If you want to use $result_array[0][0] use mysqli_fetch_row instead of mysqli_fetch_assoc

As you are fetching associative array, you have to use names as array indexes.
foreach ($result_array as $v){
echo 'key project: '.$v['key_projects'].'<br>';
echo 'contributions: '.$v['contributions'].'<hr/>';
}

Related

comparing values in 2 arrays in php - array_intersect doesn't work

I have the following arrays named investmentprogramscriteria and companyInvestmentProfil:
Array
(
[0] => Array
(
[criteriaID] => 55
[criteriaIsMatchedIf] => 11, 12, 13
)
[1] => Array
(
[criteriaID] => 54
[criteriaIsMatchedIf] => 1
)
[2] => Array
(
[criteriaID] => 52
[criteriaIsMatchedIf] => 1
)
)
Array
(
[0] => Array
(
[criteriaID] => 52
[investmentprofileCriteriaAnswer] => 1
)
[1] => Array
(
[criteriaID] => 54
[investmentprofileCriteriaAnswer] => 1
)
[2] => Array
(
[criteriaID] => 58
[investmentprofileCriteriaAnswer] => 0
)
[3] => Array
(
[criteriaID] => 59
[investmentprofileCriteriaAnswer] => 1
)
[4] => Array
(
[criteriaID] => 55
[investmentprofileCriteriaAnswer] => 1
)
)
I am trying to find out if the value of the criteriaID from the first array (investmentprogramscriteria ) exists in the second array (companyInvestmentProfil) AND IF the value of the key criteriaIsMatchedIf from the first array is equal to the value of the key investmentprofileCriteriaAnswer from the second array.
My current php code returns wrong result at this time:
if (array_intersect($investmentprogramscriteria,$companyInvestmentProfil)) {
echo "Match";
} else {
echo "Not match";
}
array_column() can extract the column indicated as a single dimension and indexes it by the next column indicated. Do this for both arrays and then use array_intersect_assoc() to check key and value:
if(array_intersect_assoc(
array_column($investmentprogramscriteria, 'criteriaIsMatchedIf', 'criteriaID'),
array_column($companyInvestmentProfil, 'investmentprofileCriteriaAnswer', 'criteriaID'))) {
echo "Match";
} else {
echo "No Match";
}
PHP >= 5.5.0 needed for array_column() or use the PHP Implementation of array_column().
You can try the code with array_map:
$elements1 = array();
foreach($investmentprogramscriteria as $item) {
$elements1[] = $item['criteriaID'] . $item['criteriaIsMatchedIf'];
}
$elements2 = array();
foreach($companyInvestmentProfil as $item) {
$elements2[] = $item['criteriaID'] . $item['criteriaIsMatchedIf'];
}
if (array_intersect($elements1, $elements2)) {
echo "Match";
} else {
echo "Not match";
}

Grouping Array by Value

I am looking to group my array into sub arrays when they have the same Supplier ID. I have looked at many similar questions on here but I cannot get any of them to work for me. I have tried foreach loops and even the PHP merge function. I have to use MySQLi for this so I cannot group using PDO.
This is what I have:
Array
(
[supplierID] => 1
[drugID] => 1
[costPrice] => 9.98
[reorderQTY] => 50
)
Array
(
[supplierID] => 1
[drugID] => 2
[costPrice] => 9.98
[reorderQTY] => 50
)
Array
(
[supplierID] => 2
[drugID] => 3
[costPrice] => 9.98
[reorderQTY] => 50
)
This is what I need:
Array
(
[supplierID] => 1
Array
(
[drugID] => 1
[costPrice] => 9.98
[reorderQTY] => 50
)
[drugID] => 2
[costPrice] => 9.98
[reorderQTY] => 50
)
)
Array
(
[supplierID] => 2
Array
(
[drugID] => 3
[costPrice] => 9.98
[reorderQTY] => 50
)
)
This is the PHP where I am outputting the array to get the above result:
if(isset($_POST["automatic"])){
$sql = "SELECT supplierID,drugID,costPrice,reorderQTY FROM drugs WHERE quantityInStock <= reorderLevel";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "<pre>";
print_r($row);// I need to sort this array into sub array groups by supplierID key
echo "</pre>";
}
}else{
echo " <tr><td>0 results </td></tr>";
}
mysqli_close($conn);
}
Something like this will do it,
$out = [];
while($row = mysqli_fetch_assoc($result)) {
$out[$row->supplierID][] = $row;
}
Basically I use the supplier id to create an array key, then assign an empty array. Then add all rows with that supplier id to that array.
This will create a multidimensional array.

PHP Combining Two Arrays Using array_combine()

But I receive 2 errors executing the code below:
Message: Undefined index: rt_default_price
Filename:
controllers/reservations.php Line Number: 24
Message: Illegal offset type
Filename: controllers/reservations.php
Line Number: 24
Line number 24 is...
$combined[] = array($key => $arrVals[$i]);
Controller (reservations.php)
$arrVals['rt_name'] = $this->reservations_model->pop_room_type(); /* This is the 1st Array:
Array
(
[rt_name] => Array
(
[0] => Array
(
[rt_name] => Business
)
[1] => Array
(
[rt_name] => Econ
)
[2] => Array
(
[rt_name] => Luxury
)
[3] => Array
(
[rt_name] => VIP
)
)
)
*/
$arrKeys['rt_default_price'] = $this->reservations_model->pop_room_price(); /* This is the 2nd Array:
Array
(
[rt_default_price] => Array
(
[0] => Array
(
[rt_default_price] => 50000
)
[1] => Array
(
[rt_default_price] => 25000
)
[2] => Array
(
[rt_default_price] => 75000
)
[3] => Array
(
[rt_default_price] => 100000
)
)
)
*/
$combined=array();
foreach ($arrKeys as $i => $key) {
$combined[] = array($key => $arrVals[$i]); // Line 24
}
/*echo "<pre>";
print_r($combined);
echo "</pre>";
Array
(
[0] => Array
(
)
)
*/
$this->load->view('/main/new_reservation', $combined);
View (main/new_reservation.php)
<?php
echo form_dropdown('room_type', $combined);
?>
Model (reservation_model.php)
function pop_room_type() {
$this->db->select('rt_name');
$query=$this->db->get('room_type');
return $query->result_array();
}
function pop_room_price() {
$this->db->select('rt_default_price');
$query=$this->db->get('room_type');
return $query->result_array();
}
I think I understand what you're trying to achieve but please correct me if I'm wrong.
$combined=array('rt_name'=>array());
foreach ($arrKeys['rt_default_price'] as $i => $defaultPrice) {
$combined['rt_name'][$i]=array(reset($defaultPrice)=>reset($arrVals['rt_name'][$i]));
}
Please note that this does depend on the indexes being the same; if that is not always the case, checking should be added to make sure the indexes exist.
The reset function returns the first element in the array.
Change this
$arrVals['rt_name'] = $this->reservations_model->pop_room_type(); /* This is the 1st Array:
to
$arrVals = $this->reservations_model->pop_room_type(); /* This is the 1st Array:
Change this
$arrKeys['rt_default_price'] = $this->reservations_model->pop_room_price(); /* This is the 2nd Array:
to
$arrKeys = $this->reservations_model->pop_room_price(); /* This is the 2nd Array:

PHP Multidimensional Associative Array - how to get list of keys?

Here is an example of my data:
[204] => Array
(
[1] => Array
(
[leads] => 9
)
[2] => Array
(
[leads] => 15
)
)
[200] => Array
(
[1] => Array
(
[leads] => 7
)
[2] => Array
(
[leads] => 16
)
[3] => Array
(
[leads] => 5
)
)
I am at the stage where I trying to output the array data into a table but how do I set up the table headers dynamically so that the columns will be 1 | 2 | 3, even if some subsets don't have an array of that type?
The array is constructed from the results of a database query like so:
$dailytotals[$store][$campaigntypeid] = array('leads'=> $leads);
I tried a for each but just realised that it wouldn't work since not all subsets have all columns.
Is there a way to get what I am trying to find?
Try this
$columns = array();
foreach ($your_array as $key=> $arr) {
$columns = array_unique(array_merge($columns, array_keys($arr)));
}
Another way
$columns = array_reduce($your_array,
function ($r, $val) {
return array_unique(array_merge($r, array_keys($val)));
},
array()
);

Counting unique arrays inside the array in PHP?

I have some array containing other arrays:
Array
(
[0] => Slip Object
(
[userId:protected] => 1
[parentSlipId:protected] => 0
[id:protected] => 25
[madeDatetime:protected] => 2011-04-19 17:13:09
[stake:protected] => 34.00
[status:protected] => 6
)
[1] => Slip Object
(
[userId:protected] => 1
[parentSlipId:protected] => 0
[id:protected] => 25
[madeDatetime:protected] => 2011-04-19 17:13:09
[stake:protected] => 34.00
[status:protected] => 6
)
[2] => Slip Object
(
[userId:protected] => 1
[parentSlipId:protected] => 0
[id:protected] => 24
[madeDatetime:protected] => 2011-04-18 11:31:26
[stake:protected] => 13.00
[status:protected] => 6
)
)
What's the best way of counting unique arrays?
Off the top of my head you could try:
$hashes = array();
$uniques = 0;
foreach($array as $slip) {
$hash = sha1(serialize($slip));
if(!in_array($hash, $hashes)) {
++$uniques;
$hashes[] = $hash;
}
}
var_dump($uniques); // prints total number of unique objects.
Edit:
#biakaveron's idea looks better though and could be adapted to:
$uniques = count(array_unique($array, SORT_REGULAR));
var_dump($uniques); // prints total number of unique objects.
This previous question has various solutions for removing duplicate arrays from within an array. If you implement any of them and then use sizeof() on the returned array you will have your solution.
eg:
<?php
$yourarray = array();
$tmp = array ();
foreach ($yourarray as $row)
if (!in_array($row,$tmp)) array_push($tmp,$row);
echo sizeof($tmp);
?>

Categories