get value from cake php multi dimention arrary - php

I have tried many things but could not get the output, would really appreciate any help
Thank you
Array (
[0] => Array ( [Toolrepos] =>
Array (
[id] => 28
[created] => 2014-12-13
[tool_type] => new1
[tool_partnum] => new3
[tool_vernum] => 57.0.5
[box_id] => 28
[request_date] => 2014-12-14
[delivered_date] => 2014-12-14 ) )
[1] => Array ( [Toolrepos] =>
Array (
[id] => 29
[created] => 2014-12-13
[tool_type] => new4
[tool_partnum] => new5
[tool_vernum] => 1.2.56
[box_id] => 28
[request_date] => 2014-12-14
[delivered_date] => 2014-12-14 ) )
[2] => Array ( [Toolrepos] =>
Array ( [id] => 29
[created] => 2014-12-13
[tool_type] => SeatApp
[tool_partnum] => sw2
[tool_vernum] => 1.1.2
[box_id] => 34
[request_date] => 2014-12-13
[delivered_date] => 2014-12-13 ) ) )
I need the output like below
if box_id = '28' then i need their corresponding values for 'created','tool_type','tool_vernum'. Sometimes I need only 'created' value for matching box_id. Thank you

$box28s = array();
$i=0;
if (! empty($arr)) {
foreach ($arr as $elem) {
$curr = ! empty($elem['Toolrepos']) ? $elem['Toolrepos'] : NULL;
if (! empty($curr)) {
foreach ($curr as $k => $v) {
if ($k == 'id' && $v == 28) {
$box28s[$i] = $curr;
}
}
}
++$i;
}
}

Related

Convert PHP array to new data-structure

I have a MYSQL query which returns the following PHP array $result:
[0] => Array (
[resourceKey] => cloth
[date] => 2020-09-06
[quantity] => 8
)
[1] => Array (
[resourceKey] => ebony
[date] => 2020-09-06
[quantity] => 4
)
[2] => Array (
[resourceKey] => gems
[date] => 2020-09-06
[quantity] => 0
)
[3] => Array (
[resourceKey] => lead
[date] => 2020-09-06
[quantity] => 0
)
[4] => Array (
[resourceKey] => limestone
[date] => 2020-09-06
[quantity] => 8
)
[5] => Array (
[resourceKey] => cloth
[date] => 2020-09-05
[quantity] => 6
)
[6] => Array (
[resourceKey] => ebony
[date] => 2020-09-05
[quantity] => 3
)
[7] => Array (
[resourceKey] => gems
[date] => 2020-09-05
[quantity] => 0
)
[8] => Array (
[resourceKey] => lead
[date] => 2020-09-05
[quantity] => 0
)
[9] => Array (
[resourceKey] => limestone
[date] => 2020-09-05
[quantity] => 6
)
And I need to convert it is a certain way to display it with jquery Datatables:
$data= array(
array("Date" => "2020-09-05","cloth"=>"6","ebony"=>"3","gems"=>"0","lead"=>"0","limestone"=>"6"),
array("Date" => "2020-09-06","cloth"=>"8","ebony"=>"4","gems"=>"0","lead"=>"0","limestone"=>"8")
);
I've been trying for a while now but can't get a good way to iterate through the results...
I have already taken care of building the columns to pass to Datatables:
$columns = array();
$columns[] = array('data' => 'Date', 'title' => 'Date');
foreach ($result as $key => $row_data) {
$newResourceKey = $myUtilities->in_array_recursive($row_data['resourceKey'], $columns);
if ($newResourceKey === FALSE) { // Only if column name not yet in array
$columns[] = array('data' => $row_data['resourceKey'], 'title' => $row_data['resourceKey']);
}
}
This is an example of the many things I've tried:
$isDateInArray = $myUtilities->in_array_recursive($row_data['date'], $data);
if ($isDateInArray === FALSE) { // Only if Date is not in array yet
array_push($data, array('Date' => $row_data['date'], $row_data['resourceKey'] => $row_data['quantity'])); // Push date and data
}
else {
array_push($data, array($row_data['resourceKey'] => $row_data['quantity'])); // Only push data. Can't find a way to add it to existing Date array
}
Update:
public function in_array_recursive($needle, $haystack, $strict = false) {
foreach ($haystack as $item) {
if (($strict ? $item === $needle : $item == $needle) || (is_array($item) && $this->in_array_recursive($needle, $item, $strict))) {
return true;
}
}
return false;
}
You can get the desired result by next simple array transformation:
$res = [];
foreach ($result as $row) {
$res[$row['date']][$row['resourceKey']] = $row['quantity'];
}
$final = [];
foreach ($res as $d=>$r) {
array_push($final, array_merge(['date'=>$d], $r));
}
print_r($final);
Here you can try the PHP code

How can i arrange array before specific array key in PHP

I would like to arrange Array before found a specific array key. For example
Following is array.
Array(
[0] => Array([package_name] => 10.4)
[1] => Array([final_total] => 10.4)
[2] => Array([package_name] => 10.5)
[3] => Array([package_name] => 4.5)
[4] => Array([final_total] => 15)
[5] => Array([package_name] => 15.2)
[6] => Array([final_total] => 15.2)
[7] => Array([package_name] => 8.4)
[8] => 8.4
)
And I want like array.
(
[0] => Array
(
[package_name] => array([0]=>10.4),
[final_total] => 10.4
)
[1] => Array
(
[package_name] => array(
[0] => 10.5,
[1] => 4.5
),
[final_total] => 15
)
[2] => Array
(
[package_name] => array([0]=>15.2)
[final_total] => 15.2
)
[3] => Array
(
[package_name] => array([0]=>8.4)
[final_total] => 8.4
)
)
So What i want If final_total key is found from array then set previous values(package_name) of final_total in a array.
Above example you can see there are 4 final_total key's of array so i want to set each package_name's value in a array that are previous value of final_total.
Following is my code.
This is my array
$main = array(array('package_name' => 10.4),array('final_total' => 10.4),array('package_name' => 10.5),array('package_name' => 4.5),array('final_total' => 15)
,array('package_name' => 15.2),array('final_total' => 15.2));
Code.
<?php
$newArray = [];
$newPackag=[];
$previousValue='';
$currentKey=0;
$PreviousKey=0;
$i=0;
$main_keys = array_keys($main);
foreach ($main as $key => $value) {
$curtent_item[] = isset($main[$key]['package_name']) ? $main[$key]['package_name'] : '';
$currentKey = $key;
if(#$main[$key]['final_total'] ==#$value['final_total']){
$previousValue = #$value['package_name'];
$newArray[] = $previousValue;
$myarray= array(#$main[$key]['package_name']);
if (array_key_exists("final_total",$main[$key])){
if($PreviousKey ==0){
$PreviousKey = $key+1;
}else{
$PreviousKey = $key;
}
}else{
$keys = array_keys($main);
$position = array_search($key, $keys);
echo "Curent Key =".$currentKey.'PreviousKey'.$PreviousKey.'</br>';
if($currentKey != $PreviousKey){
$nextKey = $keys[$currentKey+1 ];
}
$newPackag1[] = array('package_name'=>#$myarray);
}
$mainArray = array('package'=>$newPackag1);
}
$i++;
}
echo "<pre>NE page";print_r($newPackag1);
echo "<pre>";print_r($main);
anyone has better and correct solution. Above code which i am trying not able to get desire output.
Here is the snippet with modified data(surely will work for your case too),
$result = [];$i= 0;
foreach ($main as $key => $value) {
if (is_array($value)) {
$k = key($value);$v = array_shift($value);
($k != 'final_total' ? $result[$i][$k][] = $v : $result[$i][$k] = $v);
if($k == 'final_total'){
$i++;
}
} elseif (!empty($value)) {
$result[$i]['final_total'] = $value;
}
}
print_r($result);
Demo
Output:-
Array
(
[0] => Array
(
[package_name] => Array
(
[0] => 6.5
[1] => 9
)
[final_total] => 15.5
)
[1] => Array
(
[package_name] => Array
(
[0] => 10.5
)
[final_total] => 10.5
)
[2] => Array
(
[package_name] => Array
(
[0] => 17.1
)
[final_total] => 17.1
)
[3] => Array
(
[package_name] => Array
(
[0] => 9.8
)
[final_total] => 9.8
)
[4] => Array
(
[package_name] => Array
(
[0] => 16
)
[final_total] => 16
)
[5] => Array
(
[package_name] => Array
(
[0] => 10.5
)
[final_total] => 10.5
)
)

Array value sum by key value php

How can I check columnar values by associative key?
I want to check data by "building_id" . Here I have 2 buildings
then I want rent data as sum with group by "tenancy_rate"
Input array :
Array
(
[0] => Array
(
[id] => 34
[building_id] => 786
[tenancy_rate] => 0
[rent_per_room] => 10000
[management_fee_per_room] => 0
)
[1] => Array
(
[id] => 35
[building_id] => 786
[tenancy_rate] => 10
[rent_per_room] => 11810
[management_fee_per_room] => 5400
[rent] => 86050
)
[2] => Array
(
[id] => 36
[building_id] => 786
[tenancy_rate] => 20
[rent_per_room] => 11810
[management_fee_per_room] => 5400
[rent] => 86050
)
[3] => Array
(
[id] => 56
[building_id] => 798
[tenancy_rate] => 0
[rent_per_room] => 10000
[management_fee_per_room] => 5400
[rent] => 77000
)
[4] => Array
(
[id] => 57
[building_id] => 798
[tenancy_rate] => 10
[rent_per_room] => 11810
[management_fee_per_room] => 5400
[rent] => 86050
)
[5] => Array
(
[id] => 58
[building_id] => 798
[tenancy_rate] => 20
[rent_per_room] => 11810
[management_fee_per_room] => 5400
[rent] => 86050
)
)
Desired result :
Array
(
[0] => Array
(
[tenancy_rate] => 0
[rent] => 77000
)
[1] => Array
(
[tenancy_rate] => 10
[rent] => 172100
)
[2] => Array
(
[tenancy_rate] => 20
[rent] => 172100
)
)
For this I tried PHP code
But not getting any solution
$sumArray = array();
foreach ($myArray as $k=>$subArray) {
foreach ($subArray as $id=>$value) {
$sumArray[$id]+=$value;
}
}
print_r($sumArray);
Here is the snippet. To get the desired result you need to group by tenancy_rate and not by building id,
$result = [];
foreach ($arr as $val) {
// as I see, rent for some array not there, so setting it to 0
$val['rent'] = ($val['rent'] ?? 0);
if (isset($result[$val['tenancy_rate']]['rent'])) {
$result[$val['tenancy_rate']]['rent'] += $val['rent'];
} else {
$result[$val['tenancy_rate']] = [
'tenancy_rate' => $val['tenancy_rate'], 'rent' => $val['rent']];
}
}
print_r($result);
Demo
Output:-
Array
(
[0] => Array
(
[tenancy_rate] => 0
[rent] => 77000
)
[1] => Array
(
[tenancy_rate] => 10
[rent] => 172100
)
[2] => Array
(
[tenancy_rate] => 20
[rent] => 172100
)
)
You can use foreach and group by index tenancy_rate
$f = [];
foreach($a as $v){
if(!empty($f[$v['tenancy_rate']])){
$f[$v['tenancy_rate']]['rent'] += $v['rent'];
}else{
$f[$v['tenancy_rate']] = [
'tenancy_rate' => $v['tenancy_rate'],
'rent' => isset($v['rent']) ? $v['rent'] : 0
];
}
}
Working example :- https://3v4l.org/nWRGA
You can use array_values to re arrange the order of array
At first you need to use calculate rent sum for each tenancy rate:
$rentSums = [];
foreach ($input as $info) {
$tenancyRate = $info['tenancy_rate'] ?? 0;
$rent = $info['rent'] ?? 0;
$rentSum = $rentSums[$tenancyRate] ?? 0;
$rentSums[$tenancyRate] = $rentSum + $rent;
}
Then you can build the result using the data from previous step:
$result = [];
foreach ($rentSums as $tenancyRate => $rentSum) {
$result[] = [
'tenancy_rate' => $tenancyRate,
'rent' => $rentSum,
];
}
Using a function to return the necessary values (rate and rent), and accumulating the values into the sumArray array, making the assumption that the results array keys are related to the tenancy_rate (this allows for insertion of further tenancy_rates).
$sumArray = [];
function processBuildingInfo($building)
{
return [ $building['tenancy_rate']??0, $building['rent']??0 ];
}
foreach ($myArray as $k=>$subArray) {
list($rate, $rent) = processBuildingInfo($subArray);
$sumArray[$rate/10] = [
'tenancy_rate' => $rate,
'rent' => $sumArray[$rate/10]['rent'] + $rent
];
}
print_r($sumArray);
use this loop:
foreach ($myArray as $k=>$subArray) {
foreach ($subArray as $id=>$valueArray) {
$sumArray[$id]+=[
'tenancy_rate' => $valueArray['tenancy_rate'],
'rent' => $valueArray['rent']
];
}
}

Read from JSON file with PHP and Multiple foreach statements

I tried to read from a JSON file using PHP. But I am stuck now.
This is my JSON file :
Array
(
[date] => 25-1-2017
[leagues] => Array
(
[0] => Array
(
[league_id] => 0
[league_name] => كأس امم افريقيا
[league_logo] => http://3.bp.blogspot.com/-4iampWUCLto/VmldL2XTz7I/AAAAAAAAD0I/eZFfzSxRbnE/s60/africa.png
[league_matches] => Array
(
[0] => Array
(
[match_id] => 1
[team1logo] => http://2.bp.blogspot.com/-mycTzHXuzJA/Ugbb-UG_3JI/AAAAAAAAEv0/_mzaSHnRedE/s60/egypt+(4).png
[team2logo] => http://1.bp.blogspot.com/-kYrkU4jahZY/UgbeVpHf8RI/AAAAAAAAFIQ/TBgM5fvVW14/s60/ghana+(3).png
[match_time] => 19:00
[channels_id] => Array
(
[0] => 18
)
[team1] => مصر
[team2] => غانا
)
[1] => Array
(
[match_id] => 2
[team1logo] => http://3.bp.blogspot.com/-_y1MazEn-vg/UgbeoIWUpII/AAAAAAAAFPI/JTRGGpG3GiQ/s60/mali+(4).png
[team2logo] => http://2.bp.blogspot.com/-GTxKONxvKy4/Ugt6AKXOmyI/AAAAAAAAF8Y/pPcM0O58cQI/s60/uganda_2.png
[match_time] => 19:00
[channels_id] => Array
(
[0] => 19
)
[team1] => مالي
[team2] => أوغندا
)
)
)
[1] => Array
(
[league_id] => 1
[league_name] => كأس ملك أسبانيا
[league_logo] => http://1.bp.blogspot.com/-zAzWT2Vpbe0/Vmle9TUWDlI/AAAAAAAAD04/-BKgPzRCT1k/s60/Copa_del_Rey_logo_since_2012.png
[league_matches] => Array
(
[0] => Array
(
[match_id] => 3
[team1logo] => http://4.bp.blogspot.com/-6sfdkbboNdk/VBxVKisRkcI/AAAAAAAADG8/oBKDHmBW5xc/s60/eibar+fc.png
[team2logo] => http://2.bp.blogspot.com/-S7p2yMaLywM/UhCz6GqNCRI/AAAAAAAAGFE/CfxzSQk8bgQ/s60/Atletco+Madrid2.Png
[match_time] => 18:15
[channels_id] => Array
(
[0] => 1
)
[team1] => إيبار
[team2] => أتلتيكو مدريد
)
[1] => Array
(
[match_id] => 4
[team1logo] => http://1.bp.blogspot.com/--6y77FXuPLI/UjeVcpJ-AJI/AAAAAAAAGok/QyZhwahPamo/s60/Celta+Vigo.png
[team2logo] => http://2.bp.blogspot.com/-tncIAL_U6mI/UgbnQw75V8I/AAAAAAAAFhA/8-9Xpw83GKY/s60/Real+Madrid+(3).png
[match_time] => 20:15
[channels_id] => Array
(
[0] => 3
)
[team1] => سيلتا فيغو
[team2] => ريال مدريد
)
)
)
[2] => Array
(
[league_id] => 2
[league_name] => كأس الرابطة الإنجليزية
[league_logo] => http://4.bp.blogspot.com/-31G65FeskFs/VmlezHMPm_I/AAAAAAAAD0w/9OMjh8AQP-M/s60/TheFA_CapitalOneCup.png
[league_matches] => Array
(
[0] => Array
(
[match_id] => 5
[team1logo] => http://3.bp.blogspot.com/-D0lb4b-qN5U/UgbeDosqjYI/AAAAAAAAFBY/Qg7kvoodvFY/s60/Liverpool+(2).png
[team2logo] => http://2.bp.blogspot.com/-prH3jgmfewQ/Ug8ZgNxPlcI/AAAAAAAAGAU/HLmbFvGuDB8/s60/Southampton.png
[match_time] => 20:00
[channels_id] => Array
(
[0] => 2
)
[team1] => ليفربول
[team2] => ساوثهامبتون
)
)
)
[3] => Array
(
[league_id] => 3
[league_name] => كاس ايطاليا
[league_logo] => http://2.bp.blogspot.com/-p9Kjb2_GZPU/VnAdQcHV9_I/AAAAAAAAD7E/6R-P54Upui4/s60/tim-cup.png
[league_matches] => Array
(
[0] => Array
(
[match_id] => 6
[team1logo] => http://1.bp.blogspot.com/-POxAfSSnlW0/UhCt7oQsdLI/AAAAAAAAGDo/rMRXx2mqvUI/s60/Juventus[1].Png
[team2logo] => http://3.bp.blogspot.com/-_Qj_GaxVaDE/UgaEPtt7EsI/AAAAAAAAEA8/redsOTj7F4Q/s60/Ac+Milan+(3).png
[match_time] => 20:00
[channels_id] => Array
(
[0] => 103
)
[team1] => يوفنتوس
[team2] => ميلان
)
)
)
)
)
And this is my PHP so far:
$str = file_get_contents($url);
$json = json_decode($str, true);
$date = $json['date'];
$leagues = $json['leagues'][0];
foreach ($leagues as $key => $value) {
for ($i=0; $i<count($value); $i++) {
foreach ($value[$i] as $key1 => $value1) {
$sql = "INSERT INTO table_name (column1,column2,column3,column4) VALUES (...,...,...,...)";
for ($c=0; $c<count($value1); $c++) {
foreach ($value1[$c] as $key2 => $value2) {
echo $value2;
}
}
}
}
}
the problem how can read all each array by foreach and store every value to table in database.
I would appreciate an example for this.
Basic structure to loop all nodes in your json
//leagues level
foreach ($json['leagues'] as $key => $league) {
$league_id = $league['league_id'];
//leagues -> league_matches level
foreach ($league['league_matches'] as $key => $match) {
$match_id = $match['match_id'];
//channel ids
foreach ($match['channels_id'] as $channels_id) {
//$channels_id;
//create an sql
$sql = "INSERT INTO xy (col1,col2,col3) values ($league_id,$match_id,$channels_id)";
$db->query($sql);
}
}
}
About the SQL You dont show any structure of your databse, so i cant help creating the sql.
I hope your JSON file sends the value using json_encode() method. You need to separate the array elements with a comma (,). Also you need to write the array indexes within quotes ('). Here is a corrected sample of your JSON page.
$retArr = Array
(
['date'] => 25-1-2017,
['leagues'] => Array
(
[0] => Array
(
['league_id'] => 0,
['league_name'] => كأس امم افريقيا,
['league_logo'] => http://3.bp.blogspot.com/-4iampWUCLto/VmldL2XTz7I/AAAAAAAAD0I/eZFfzSxRbnE/s60/africa.png,
['league_matches'] => Array
(
[0] => Array
(
['match_id'] => 1,
['team1logo'] => http://2.bp.blogspot.com/-mycTzHXuzJA/Ugbb-UG_3JI/AAAAAAAAEv0/_mzaSHnRedE/s60/egypt+(4).png,
['team2logo'] => http://1.bp.blogspot.com/-kYrkU4jahZY/UgbeVpHf8RI/AAAAAAAAFIQ/TBgM5fvVW14/s60/ghana+(3).png,
['match_time'] => 19:00
['channels_id'] => Array
(
[0] => 18
)
['team1'] => مصر ,
['team2'] => غانا
)
)
)
)
);
echo json_encode($retArr);
On the receiving page, you need to set a second parameter to TRUE in the json_decode() method so that you will get the result as an array rather than as a JSON Object.
$str = file_get_contents($url);
$json = json_decode($str, true);
$date = $json['date'];
$leagues = $json['leagues'][0];
foreach ($leagues as $key => $value) {
for ($i=0; $i<count($value); $i++) {
foreach ($value[$i] as $key1 => $value1) {
$sql = "INSERT INTO table_name (column1,column2,column3,column4) VALUES (...,...,...,...)";
for ($c=0; $c<count($value1); $c++) {
foreach ($value1[$c] as $key2 => $value2) {
echo $value2;
}
}
}
}
}
Try this way.

Group data from two 2d arrays by three columns and retaining the lowest value in another column within each group

I have 2 multidimensional Arrays with Flightdates (Price, Date, Airline,..). I want to merge and remove duplicates that have the same date but I need to keep the cheaper one. I have always the same flight, but different prices.
$array1 = array(
[0] => Array
(
[price] => 191
[date1] => 22-07-2016
[date2] => 30-07-2016
[airline] => Lufthansa
)
[1] => Array
(
[price] => 80
[date1] => 25-07-2016
[date2] => 30-07-2016
[airline] => Easyjet
)
[2] => Array
(
[price] => 243
[date1] => 10-08-2016
[date2] => 36-08-2016
[airline] => Airberlin
)
);
$array2 = array(
[0] => Array
(
[price] => 230
[date1] => 22-07-2016
[date2] => 30-07-2016
[airline] => Lufthansa
)
[1] => Array
(
[price] => 80
[date1] => 25-07-2016
[date2] => 30-07-2016
[airline] => Easyjet
)
[2] => Array
(
[price] => 200
[date1] => 10-08-2016
[date2] => 36-08-2016
[airline] => Airberlin
)
);
Just loop through the first array and match the price in second array with respect to key of first array and push the values into into new array..
First Answer
<?php
$newArray = array();
foreach($array1 as $key =>$val)
{
if($val['price'] <= $array2[$key]['price'])
{
$newArray[] = $val;
}
else
{
$newArray[] = $array2[$key];
}
}
print_r($newArray);
?>
LIVE EXAMPLE : CLICK HERE
Second Answer
$newArray = array();
foreach($array1 as $key => $val)
{
foreach($array2 as $k => $v)
{
if($val['date1'] == $v['date1'] && $val['date2'] == $v['date2'] && $val['airline'] == $v['airline'])
{
if($val['price'] <= $array2[$key]['price'])
{
$newArray[] = $val;
}
else
{
$newArray[] = $v;
}
}
}
}
print_r($newArray);
LIVE EXAMPLE : CLICK HERE
This will give you :
Array
(
[0] => Array
(
[price] => 191
[date1] => 22-07-2016
[date2] => 30-07-2016
[airline] => Lufthansa
)
[1] => Array
(
[price] => 80
[date1] => 22-07-2016
[date2] => 30-07-2016
[airline] => Easyjet
)
[2] => Array
(
[price] => 200
[date1] => 22-07-2016
[date2] => 30-07-2016
[airline] => Airberlin
)
)

Categories