Loop through array and output links based on number of arrays - php

I currently have an array as follows:
Array (
[0] => Array ( [id] => 34 [another_id] => 2805 [third_id] => 1 )
[1] => Array ( [id] => 35 [another_id] => 2805 [third_id] => 1 )
[2] => Array ( [id] => 36 [another_id] => 2805 [third_id] => 1 )
[3] => Array ( [id] => 37 [another_id] => 2805 [third_id] => 1 )
[4] => Array ( [id] => 38 [another_id] => 2805 [third_id] => 1 )
[5] => Array ( [id] => 39 [another_id] => 2805 [third_id] => 1 )
[6] => Array ( [id] => 40 [another_id] => 2805 [third_id] => 2 )
[7] => Array ( [id] => 41 [another_id] => 2805 [third_id] => 2 )
[8] => Array ( [id] => 42 [another_id] => 2805 [third_id] => 2 )
[9] => Array ( [id] => 43 [another_id] => 2805 [third_id] => 2 )
)
What I need to do is ultimately print out 9 links ( as there are 9 array elements) but based on the keys in the array. For example:
www.samplelink/link/id/another_id/third_id
But I can't seem to get the loop right. What I have so far is:
foreach ($array as $arr) {
foreach ( $arr as $key => $value ) {
echo "<a>www.samplelink/link/".$key[$value]."</a>";
}
}
But thats not exactly what I need as its printing out the keys as well. Anyone know what I could do?

foreach ($array as $innerArray) {
echo "<a>www.samplelink/link/".$innerArray['id']."/".$innerArray['another_id']."/".$innerArray['third_id']."</a>";
}
It can give an undefined index error if key doesn't exist so you can do something like this as well:
foreach ($array as $innerArray) {
$finalLink = array_key_exists('id',$innerArray)?$innerArray['id']:"";
$finalLink.= "/".array_key_exists('another_id',$innerArray)?$innerArray['another_id']:"";
$finalLink.= "/".array_key_exists('third_id',$innerArray)?$innerArray['third_id']:"";
echo "<a>www.samplelink/link/$finalLink</a>";
}

If elements in subarrays always in same order, you can just implode them:
foreach ($array as $arr) {
echo "<a>www.samplelink/link/".implode('/', $arr)."</a>";
}
Otherwise you should point what index will be in which position explicitly, as in #Danyal Sandeelo's answer.

<?php
$arrays = array(
"0" => array('id' => 30, 'another_id' => 2800, 'third_id' => 1),
"1" => array('id' => 31, 'another_id' => 2801, 'third_id' => 1),
"2" => array('id' => 32, 'another_id' => 2802, 'third_id' => 1),
"3" => array('id' => 33, 'another_id' => 2803, 'third_id' => 1),
"4" => array('id' => 34, 'another_id' => 2804, 'third_id' => 1),
"5" => array('id' => 35, 'another_id' => 2805, 'third_id' => 2),
"6" => array('id' => 36, 'another_id' => 2806, 'third_id' => 3),
"7" => array('id' => 37, 'another_id' => 2807, 'third_id' => 3),
"8" => array('id' => 38, 'another_id' => 2808, 'third_id' => 2),
"9" => array('id' => 39, 'another_id' => 2809, 'third_id' => 2),
);
foreach($arrays as $key => $array) {
echo 'www.samplelink/link/'.$array['id'].'/'.$array['another_id'].'/'.$array['third_id']. "\n";
}
you can play with it here http://sandbox.onlinephpfunctions.com/code/1c7838e25045263de03e23c60b19c86d5640407d

You can do this :
foreach ($array as $arr) {
echo "<a>www.samplelink/link/" . $arr['id'] . '/' . $arr['another_id'] . '/' . $arr['third_id'] . "</a>";
}
or, if your sub-arrays always holds the ids in the proper order and nothing but the relevant ones :
foreach ($array as $arr) {
echo "<a>www.samplelink/link/" . implode('/', $arr) . "</a>";
}

$value will hold the inner array on each iteration.
foreach($array as $value) {
$link = '//www.samplelink/link/'.$value['id'].'/'.$value['another_id'].'/'.$value['third_id']
echo '<a>'.$link.'</a>';
}

Related

Converting Array type in PHP

Please Help in conversion of an array from one form to another I Have This Array
Array (
[mpr_last_month] => 376431
[mpr_month] => 03
[total_boys_all_6m_36m] => 5550225
[total_girls_all_6m_36m] => 5215529
[total_boys_all_36m_72m] => 4209639
[total_girls_all_36m_72m] => 4149613
[total_pse_boys_36m_72m] => 4442301
[total_pse_all_girls_36m_72m] => 4413446
[total_pregnanting] => 2209158 )
Array (
[mpr_last_month] => 448216
[mpr_month] => 04
[total_boys_all_6m_36m] => 7153209
[total_girls_all_6m_36m] => 6798913
[total_boys_all_36m_72m] => 5175846
[total_girls_all_36m_72m] => 5105460
[total_pse_boys_36m_72m] => 5290617
[total_pse_all_girls_36m_72m] => 5263340
[total_pregnanting] => 2944612
)
Array (
[mpr_last_month] => 448253
[mpr_month] => 05
[total_boys_all_6m_36m] => 11742417
[total_girls_all_6m_36m] => 6362815
[total_boys_all_36m_72m] => 4879252
[total_girls_all_36m_72m] => 4756805
[total_pse_boys_36m_72m] => 5344042
[total_pse_all_girls_36m_72m] => 5095155
[total_pregnanting] => 2852864
)
Array (
[mpr_last_month] => 470848
[mpr_month] => 06
[total_boys_all_6m_36m] => 6552523
[total_girls_all_6m_36m] => 6217771
[total_boys_all_36m_72m] => 4613019
[total_girls_all_36m_72m] => 4551685
[total_pse_boys_36m_72m] => 5182666
[total_pse_all_girls_36m_72m] => 5165730
[total_pregnanting] => 2746293
)
Array (
[mpr_last_month] => 465489
[mpr_month] => 07
[total_boys_all_6m_36m] => 6638749
[total_girls_all_6m_36m] => 6310676
[total_boys_all_36m_72m] => 4801665
[total_girls_all_36m_72m] => 4657764
[total_pse_boys_36m_72m] => 5020964
[total_pse_all_girls_36m_72m] => 5051785
[total_pregnanting] => 2815773
)
I Want This
name: 'mpr_last_month',
data: [43934, 52503, 57177, 69658, 97031, 119931, 137133, 154175,123,123,123,123]
.
.
.
.
.
.
.
.
Simplest approach would be foreach loop.
$newData = [];
foreach ($yourArray as $innerArray) {
foreach ($innerArray as $key => $value) {
$newData[$key][] = $value;
}
}
It loops over the first array (the big one, containg all others), the runs over each inner array and store the value in the correct place.
You can use array_column function. But be aware that this function works only for PHP >= 5.5.0. Try this:
//example data
$array = [
['a' => 2, 'b'=>3, 'c'=>6],
['a' => 12, 'b'=>13, 'c'=>16],
['a' => 22, 'b'=>23, 'c'=>26],
];
$result = [];
//get indexes from first element of array
$indexes = array_keys($array[0]);
foreach($indexes as $index) {
$result[$index] = array_column($array, $index);
}
And result is:
Array
(
[a] => Array
(
[0] => 2
[1] => 12
[2] => 22
)
[b] => Array
(
[0] => 3
[1] => 13
[2] => 23
)
[c] => Array
(
[0] => 6
[1] => 16
[2] => 26
)
)

Find how many arrays with valid keys in multidimensional array in php

I need to know how many arrays have valid keys, how many arrays with valid keys in multidimensional array. Let me explain:
Input:
Array
(
[65] => Array
(
[1] => Array
(
[0] => Array
(
[mediumid] => 65
[mediumname] => VINYL
[trackid] => 525
[trackposition] => 1
[tracklocation] => SIDE A
[tracknumber] => 1
[trackname] => I love u
)
[1] => Array
(
[mediumid] => 65
[mediumname] => VINYL
[trackid] => 526
[trackposition] => 1
[tracklocation] => SIDE A
[tracknumber] => 2
[trackname] => Sun is yellow
)
)
[2] => Array
(
[0] => Array
(
[mediumid] => 65
[mediumname] => VINYL
[trackid] => 527
[trackposition] => 2
[tracklocation] => SIDE B
[tracknumber] => 1
[trackname] => Car red
)
[1] => Array
(
[mediumid] => 65
[mediumname] => VINYL
[trackid] => 528
[trackposition] => 2
[tracklocation] => SIDE B
[tracknumber] => 2
[trackname] => Lady in red
)
)
)
[769] => Array
(
[] => Array
(
[0] => Array
(
[mediumid] => 769
[mediumname] => DVD
[trackid] =>
[trackposition] =>
[tracklocation] =>
[tracknumber] =>
[trackname] =>
)
)
)
)
The mediums[65] next array contains 2 valid keys (1 and 2). The mediums[769] next array contains no valid keys
Therefore only mediums[65] contains valid keys, so total of arrays with valid keys = 1.
I need to find that total. How ?
I've try using array_keys and array_filter, with no success (or either i'm doing it wrong)
PHP code demo
<?php
$array=Array
(
65 => Array
(
1 => Array
(
0 => Array
(
"mediumid" => 65,
"mediumname" => "VINYL",
"trackid" => 525,
"trackposition" => 1,
"tracklocation" => "SIDE A",
"tracknumber" => 1,
"trackname" => "I love u"
),
1 => Array
(
"mediumid" => 65,
"mediumname" => "VINYL",
"trackid" => 526,
"trackposition" => 1,
"tracklocation" => "SIDE A",
"tracknumber" => 2,
"trackname" =>"Sun is yellow"
)
),
2 => Array
(
0 => Array
(
"mediumid" => 65,
"mediumname" => "VINYL",
"trackid" => 527,
"trackposition" => 2,
"tracklocation" => "SIDE B",
"tracknumber" => 1,
"trackname" => "Car red"
),
1 => Array
(
"mediumid" => 65,
"mediumname" => "VINYL",
"trackid" => 528,
"trackposition" => 2,
"tracklocation" => "SIDE B",
"tracknumber" => 2,
"trackname" => "Lady in red"
)
)
),
769 => Array
(
"" => Array
(
0 => Array
(
"mediumid" => 769,
"mediumname" => "DVD",
"trackid" => "",
"trackposition" => "",
"tracklocation" => "",
"tracknumber" =>"",
"trackname" => ""
)
)
)
);
$counter=0;
$trackedNull=false;
foreach($array as $key => $value)
{
$keys=array_keys($array[$key]);
foreach($keys as $arraykey)
{
if($arraykey=="")
{
$trackedNull=true;
break;
}
}
if($trackedNull==true)
{
$trackedNull=false;
}
else
{
$counter++;
}
}
echo $counter;

Have the following array merged

I have the following array:
Array
(
[0] => Array
(
[Vendor_ID] => 1
[Quantity] => 55
)
[1] => Array
(
[Vendor_ID] => 1
[Quantity] => 55
)
[2] => Array
(
[Vendor_ID] => 1
[Quantity] => 55
)
[3] => Array
(
[Vendor_ID] => 3
[Quantity] =>
)
[4] => Array
(
[Vendor_ID] => 3
[Quantity] =>
)
[5] => Array
(
[Vendor_ID] => 3
[Quantity] =>
)
[6] => Array
(
[Vendor_ID] => 4
[Quantity] =>
)
[7] => Array
(
[Vendor_ID] => 4
[Quantity] =>
)
[8] => Array
(
[Vendor_ID] => 4
[Quantity] =>
)
)
Which is being created with the following code:
$Display_Arr = array();
$Tick = 0;
foreach ($_POST['product'] AS $_1){
if (!in_array($_1['vendor_id'], $Display_Arr)){
$Display_Arr[$Tick] = array(
"Vendor_ID" => $_1['vendor_id'],
"Quantity" => ""
);
$Display_Arr[$Tick]["Quantity"] .= $_1['quantity'];
}else{
$Display_Arr[$Tick]["Quantity"] .= $_1['quantity'];
}
++$Tick;
}
echo "<pre>";
print_r($Display_Arr);
echo "</pre>";
But I am not getting my desired output, which is:
Array
(
[0] => Array
(
[Vendor_ID] => 1
[Quantity] => 55,55,55
)
[1] => Array
(
[Vendor_ID] => 3
[Quantity] =>
)
[2] => Array
(
[Vendor_ID] => 4
[Quantity] =>
)
)
Where am I going wrong with this?
#mathielo
The current output is:
Array
(
[1] => Array
(
[Vendor_ID] => 1
[Quantity] => 55
)
[3] => Array
(
[Vendor_ID] => 3
[Quantity] =>
)
[4] => Array
(
[Vendor_ID] => 4
[Quantity] =>
)
)
Whereas, i'm trying to obtain:
[0] => Array
(
[Vendor_ID] => 1
[Quantity] => 55,55,55
)
If I got it right, what you need is this:
EDIT: Just made some tests and got it right this time:
$Display_Arr = array();
foreach ($_POST['product'] AS $_1){
if (!array_key_exists($_1['Vendor_ID'], $Display_Arr)){
$Display_Arr[$_1['Vendor_ID']] = array(
"Vendor_ID" => $_1['Vendor_ID'],
"Quantity" => $_1['Quantity']
);
}else{
if(!empty($_1['Quantity']))
$Display_Arr[$_1['Vendor_ID']]["Quantity"] .= ",{$_1['Quantity']}";
}
}
echo "<pre>";
print_r($Display_Arr);
echo "</pre>";
The main problem was in if (!in_array($_1['vendor_id'], $Display_Arr)). PHP's in_array() checks for given needle in the array values, and we were trying to match to the Vendor_ID value stored in the outer array keys. That was fixed using array_key_exists().
EDIT 2: I used this for test data:
$_POST['product'] = array(
0 => array(
'Vendor_ID' => 1,
'Quantity' => 55
),
1 => array(
'Vendor_ID' => 1,
'Quantity' => 55
),
2 => array(
'Vendor_ID' => 1,
'Quantity' => 55
)
,
3 => array(
'Vendor_ID' => 3,
'Quantity' => ''
),
4 => array(
'Vendor_ID' => 3,
'Quantity' => ''
),
5 => array(
'Vendor_ID' => 3,
'Quantity' => ''
),
6 => array(
'Vendor_ID' => 4,
'Quantity' => ''
),
7 => array(
'Vendor_ID' => 4,
'Quantity' => ''
),
8 => array(
'Vendor_ID' => 4,
'Quantity' => ''
)
);
You won't be needing $Tick anymore, as you could use Vendor_ID as keys for the outer array.
Looks like the easiest way to solve this would be to first aggregate the vendor quantities, and then build the final array with the keys that you are using.
I am assuming the input looks something like this:
$_POST['product'] = [
['vendor_id' => 1, 'quantity' => 55],
['vendor_id' => 1, 'quantity' => 55],
['vendor_id' => 1, 'quantity' => 55],
['vendor_id' => 3, 'quantity' => null],
['vendor_id' => 3, 'quantity' => null],
['vendor_id' => 3, 'quantity' => null],
['vendor_id' => 4, 'quantity' => null],
['vendor_id' => 4, 'quantity' => null],
['vendor_id' => 4, 'quantity' => null],
];
Aggregating the quantities:
$aggregates = [];
foreach ($_POST['product'] as $product) {
$id = $product['vendor_id'];
if ( ! isset($aggregates[$id])) {
$aggregates[$id] = [];
}
if ($product['quantity'] > 0) {
$aggregates[$id][] = $product['quantity'];
}
}
The aggregates array should now look like this:
$aggregates = [
1 => [
0 => 55,
1 => 55,
2 => 55,
],
3 => [], // Empty
4 => [], // Empty
];
As you can see the data is now neatly organized and ready to be put into any format you want. Using the keys that you use in your question it is as simple as:
$output = [];
foreach ($aggregates as $vid => $qty) {
$quantity = implode(',', $qty);
$output[] = ['Vendor_ID' => $vid, 'Quantity' => $quantity];
}
The output should now look like this:
$output = [
['Vendor_ID' => 1, 'Quantity' => '55,55,55'],
['Vendor_ID' => 3, 'Quantity' => ''],
['Vendor_ID' => 4, 'Quantity' => ''],
];
This will output exactly what you are looking for although the output of the last answer (Sverri M. Olsen) is more useful. Here you get the quantities as a string while with Sverri's method you get an array in first place.
$Display_Arr = array();
$vendors=array();
foreach ($_POST['product'] AS $_1){
if (!in_array($_1['vendor_id'],$vendors)){
$vendors[]=$_1['vendor_id'];
$Display_Arr[sizeof($vendors)-1] = array(
"Vendor_ID" => $_1['vendor_id'],
"Quantity" => $_1['quantity']
);
}
else{
$vendorKey=array_search($_1['vendor_id'],$vendors);
$Display_Arr[$vendorKey]["Quantity"] .=(!empty($Display_Arr[$vendorKey]["Quantity"])?',':null).$_1['quantity'];
}
}

Summing The Contents Of A Three Tiered Array PHP

This is the array I am using (3 tiers), and I am trying to add the number of sales (nosales) from the first month in the first array to the first month in the second array (Should be 150) and so on through all the variables (months shouldn't be added) so I am left with a two level array with the nosales, salevalue,salecost and saleprofit totals for each month.
Array (
[0] => Array
(
[1] => Array
(
[month] => 1
[nosales] => 100
[salevalue] => 1200
[salecost] => 360
[saleprofit] => 840
)
[2] => Array
(
[month] => 2
[nosales] => 110
[salevalue] => 1320
[salecost] => 396
[saleprofit] => 924
)
)
[1] => Array
(
[1] => Array
(
[month] => 1
[nosales] => 50
[salevalue] => 350
[salecost] => 70
[saleprofit] => 280
)
[2] => Array
(
[month] => 2
[nosales] => 55
[salevalue] => 385
[salecost] => 77
[saleprofit] => 308
)
)
)
Now, I have tried looping through them to get them to add together but I am getting a number of errors. Could someone please help?
Here is the script I am using at the moment:
$acc = array_shift($results_array);
foreach ($results_array as $val) {
foreach ($val as $v) {
foreach ($v as $key => $v){
$acc[$key] += $v;
}
}
}
Thanks for your help in advance!
Is this what you wanted to do?
$aResultsArray = array(
0 => array(
1 => array(
'month' => 1,
'nosales' => 100,
'salevalue' => 1200,
'saleconst' => 360,
'saleprofit' => 840,
),
2 => array(
'month' => 2,
'nosales' => 110,
'salevalue' => 1320,
'saleconst' => 396,
'saleprofit' => 924,
),
),
1 => array(
1 => array(
'month' => 1,
'nosales' => 50,
'salevalue' => 350,
'saleconst' => 70,
'saleprofit' => 280,
),
2 => array(
'month' => 2,
'nosales' => 55,
'salevalue' => 385,
'saleconst' => 77,
'saleprofit' => 308,
),
),
);
$aSum = array();
foreach ($aResultsArray as $mYear => $aMonths) {
foreach ($aMonths as $mMonth => $aMonth) {
if (!isset($aSum[$aMonth['month']])) {
$aSum[$aMonth['month']] = array(
'month' => $aMonth['month'],
'nosales' => 0,
'salevalue' => 0,
'saleconst' => 0,
'saleprofit' => 0,
);
}
$aSum[$aMonth['month']]['nosales'] += $aMonth['nosales'];
$aSum[$aMonth['month']]['salevalue'] += $aMonth['salevalue'];
$aSum[$aMonth['month']]['saleconst'] += $aMonth['saleconst'];
$aSum[$aMonth['month']]['saleprofit'] += $aMonth['saleprofit'];
}
}
var_dump($aSum);

Searching for a value inside an array and getting the array

I am trying to use an array to search for a value that is inside of an array and then take the full array that the value is in and add it to an array. Below is the array to get the value from:
Array (
[0] => Array ( [ID] => 138 [dimmer] => 5 [order] => 1 [double] => 0 [location1] => DSR [location2] => Stage Pockets )
[1] => Array ( [ID] => 139 [dimmer] => 6 [order] => 1 [double] => 0 [location1] => DSR [location2] => Stage Pockets )
[2] => Array ( [ID] => 140 [dimmer] => 7 [order] => 2 [double] => 0 [location1] => DSR [location2] => Stage Pockets )
[3] => Array ( [ID] => 141 [dimmer] => 8 [order] => 2 [double] => 0 [location1] => DSR [location2] => Stage Pockets )
)
I am trying to get the value of dimmer with the search function below:
function search($array, $key, $value)
{
$results = array();
if (is_array($array))
{
if (isset($array[$key]) && $array[$key] == $value)
$results[] = $array;
foreach ($array as $subarray)
$results = array_merge($results, search($subarray, $key, $value));
}
return $results;
}
Below it uses the $chan value which is an integer to use the function above to search an array. The foreach is then supposed to go through the array that is $patch and select the arrays out of the array above (only returns an empty array), although it doesn't do that unless you change $patch_single['dimmer'] with a string such as "7".
$patch = search($patch, 'Channel', $chan);
foreach ($patch as $patch_single) {
print_r($patch_single);
$dim_single = intval($patch_single['dimmer']);
echo $dim_single;
$dimmers = search($dimmers, 'dimmer', $dim_single);
}
The array that is being used to get $patch_single['dimmer'] is, when inside the foreach:
Array ( [ID] => 241 [Channel] => 100 [dimmer] => 7 )
Array ( [ID] => 242 [Channel] => 100 [dimmer] => 25 )
Thank you for your advice.
Hm, i see that you have 2 dimensional array. Why you just don't use this?
foreach($array as $row) {
if ($row['dimmer'] == $myValue) { $newArray[] = $row; }
}
Try this :
$arr = Array (Array ( "ID" => 138, "dimmer" => 5, "order" => 1, "double" => 0, "location1" => "DSR", "location2" => "Stage Pockets" ),
Array ( "ID" => 139, "dimmer" => 6, "order" => 1, "double" => 0, "location1" => "DSR", "location2" => "Stage Pockets" ),
Array ( "ID" => 140, "dimmer" => 7, "order" => 2, "double" => 0, "location1" => "DSR", "location2" => "Stage Pockets" ),
Array ( "ID" => 141, "dimmer" => 8, "order" => 2, "double" => 0, "location1" => "DSR", "location2" => "Stage Pockets" ));
$arr = array_filter($arr, function($ar) {
return ($ar['dimmer'] == '7' );
});
echo "<pre>";
print_r($arr);
Output :
Array
(
[2] => Array
(
[ID] => 140
[dimmer] => 7
[order] => 2
[double] => 0
[location1] => DSR
[location2] => Stage Pockets
)
)
ref: http://php.net/manual/en/function.array-filter.php

Categories