I am new to PHP and am trying to apply a named array within a named array. I have been able to apply each rope name (i.e. "Poly Soak") along with img, title, blurb, desc, etc. but am having a difficult time trying to apply $specTable into a table. I am also trying to apply $applications and $benefits with no luck.
I am using the using the GET command to generate each page. Pages populate as follows:
water-rescue-ropes.php?value=aqua-d
water-rescue-ropes.php?value=poly-soak... etc
function strip_bad_chars( $input ) {
$output = preg_replace( "/[^a-zA-Z0-9_-]/", "", $input );
return $output; }
if (isset($_GET['value'])) {
$waterRescueRope = strip_bad_chars( $_GET['value'] );
$rope = $waterRescueRopes[$waterRescueRope];}
Here is the edited array info:
$waterRescueRopes = array(
"poly-soak" => array(
'img' => "3P",
'title' => "Poly Soak™",
'blurb' => "Pelican’s 16 strand kernmantle construction is a...",
'desc' => "Polypropylene Water Rescue Rope",
'construction' => "16 Strand",
'cover' => "Polypropylene",
'core' => "Polypropylene",
array(
array(
'sku' => "3P-12Y",
'diameter' => "3/8"",
'tensile' => 3000,
'weight' => 3.4,
),
array(
'sku' => "3P-14Y",
'diameter' => "7/16"",
'tensile' => 3380,
'weight' => 4.7,
),
),
array("Water Rescue", "Canyoneering"),
array("Lightweight", "Buoyant", "High Visibility"),
),
"poly-soak-economy" => array(
'img' => "FQK",
'title' => "Poly Soak™ Economy",
'blurb' => "All the great benefits and features of our Poly Soak rope but at a lower cost.",
'desc' => "Polypropylene Economy Water Rescue Rope",
'construction' => "16 Strand",
'cover' => "Polypropylene",
'core' => "Polypropylene",
array(
array(
'sku' => "FQK-502",
'diameter' => "1/8"",
'tensile' => 2000,
'weight' => 1.5,
),
),
array("Water Rescue"),
array("Economical", "Lightweight", "Buoyant"),
),
"poly-soak-2" => array(
'img' => "3PN",
'title' => "Poly Soak™",
'blurb' => "This UL certified polypropylene rope is approved for...",
'desc' => "NFPA® Water Rescue Rope",
'construction' => "24 Strand",
'cover' => "Polypropylene",
'core' => "Polypropylene",
array(
array(
'sku' => "3PN-12Y",
'diameter' => "3/8"",
'tensile' => 4200,
'weight' => 3.05,
),
),
array("Water Rescue", "Canyoneering", "Mooring"),
array("Bright Colors for Greater Visibility", "Supple for Compact Storage", "Certified to the Highest Standard", "Buoyant"),
),
"aqua-d" => array(
'img' => "3q",
'title' => "Aqua-D™",
'blurb' => "This water rescue rope has a blended Dyneema® and polypropylene core. With a multifilament polypropylene cover, this rope floats and has near zero water retention. It is extremely strong, light 'weight', and has a no-stretch braid that meets the needs of coastal and river rescue professionals worldwide.",
'desc' => "Dyneema® Polypropylene Water Rescue Rope",
'construction' => "16 Strand",
'cover' => "Polypropylene",
'core' => "Dyneema®",
array(
array(
'sku' => "3Q-08Y",
'diameter' => "1/4"",
'tensile' => "3200",
'weight' => "1.7",
),
array(
'sku' => "3Q-10Y",
'diameter' => "5/16"",
'tensile' => "3400",
'weight' => "2.3",
),
array(
'sku' => "3Q-12Y",
'diameter' => "3/8"",
'tensile' => "4950",
'weight' => "3.4",
),
),
array("Minimal Water Retention", "Strong & Lightweight", "Buoyant"),
array("Water Rescue"),
), );
Additional included functions:
function get_specs($array = false)
{
if (!is_array($array))
return array();
elseif(empty($array))
return array();
foreach($array as $polytype => $polydata) {
$new[$polytype]['specs'] = (!empty($polydata[0]))? $polydata[0]:array();
$new[$polytype]['applications'] = (!empty($polydata[1]))? $polydata[1]:array();
$new[$polytype]['benefits'] = (!empty($polydata[2]))? $polydata[2]:array();
}
return $new;
}
Here is the edited specTable:
<?php function display_specs($spec = array(),$name = false)
{
if(!empty($spec[$name]['specs'])) {
ob_start();
foreach($spec[$name]['specs'] as $specs) {
?>
<tr>
<td><?php echo $specs['sku']; ?></td>
<td><?php echo $specs['diameter']; ?></td>
<td><?php echo $specs['tensile']; ?></td>
<td><?php echo $specs['weight']; ?></td>
</tr>
<?php
}
$data = ob_get_contents();
}
} ?>
// Isolates the specs from the main array
$specs = get_specs($waterRescueRopes);
// Alternately, you can loop through the main array and get all
<?php foreach($specs as $polytype => $spec) {
echo display_specs($specs,$_GET['value']);
}
?>
Edited Applications (Benefits is in similar list):
<?php function display_applications($spec = array(),$name = false)
{
if(!empty($spec[$name]['applications'])) {
ob_start();
foreach($spec[$name]['applications'] as $apps) {
?>
<li><?php echo $apps; ?></li>
<?php
}
$data = ob_get_contents();
return $data;
}
}
?>
<tr valign='top'>
<td class="td-item-cell"><article>
<div class="rel_product_wrapper">
<h3>Applications</h3>
<ul>
<li>
<?php
foreach($specs as $polytype => $spec) {
echo display_applications($specs,$_GET['value']);
}
?>
</li>
</ul>
</div>
</article></td>
</tr>
I currently have them populating what I need but multiple times ( four times for the four types of rope, I am assuming).
Thank you for your time! I appreciate it! :)
Remove the variables in your array, then create a function to extract just those aspects you need separately. The reason what you are doing does not work is because each time you write $specTable on each array, you re-assign/overwrite the previously-assigned $specTable to the current array until finally it is assigned the last array in the main array. That is why only one shows up. You need to save out those aspects to new arrays:
FUNCTIONS: Place functions at the top of the page OR in a different file that you include on this page for use. It is better to include using something like include("function.specs.php") because then you can reuse the functions on different pages if you want.
function get_specs($array = false)
{
if (!is_array($array))
return array();
elseif(empty($array))
return array();
foreach($array as $polytype => $polydata) {
$new[$polytype]['specs'] = (!empty($polydata[0]))? $polydata[0]:array();
$new[$polytype]['applications'] = (!empty($polydata[1]))? $polydata[1]:array();
$new[$polytype]['benefits'] = (!empty($polydata[2]))? $polydata[2]:array();
}
return $new;
}
function display_specs($spec = array(),$name = false)
{
if(!empty($spec[$name]['specs'])) {
ob_start();
foreach($spec[$name]['specs'] as $specs) {
?>
<tr>
<td><?php echo $specs['sku']; ?></td>
<td><?php echo $specs['diameter']; ?></td>
<td><?php echo $specs['tensile']; ?></td>
<td><?php echo $specs['weight']; ?></td>
</tr>
<?php
}
$data = ob_get_contents();
return $data;
}
}
// For sake of ease, you can do an application one by itself,
// Normally, you could just do one class/method that handles all the
// the different arrays
function display_applications($spec = array(),$name = false)
{
if(!empty($spec[$name]['applications'])) {
ob_start();
foreach($spec[$name]['applications'] as $apps) {
?>
<tr>
<td><?php echo $apps; ?></td>
</tr>
<?php
}
$data = ob_get_contents();
return $data;
}
}
Using the functions on your page:
// Isolates the specs from the main array
$specs = get_specs($waterRescueRopes);
// To select one product out of the bunch, just use the name from the array.
// Note, you need the $specs array as the first argument
echo display_specs($specs,"poly-soak");
echo display_applications($specs,"poly-soak");
// Alternately, you can loop through the main array and get all: ?>
<table>
<?php
foreach($specs as $polytype => $spec) {
echo display_specs($specs,$polytype);
echo display_applications($specs,$polytype);
}
?>
</table>
Applications Part: Because the function already does the loop for you, you just need to echo it:
<tr valign='top'>
<td class="td-item-cell"><article>
<div class="rel_product_wrapper">
<h3>Applications</h3>
<ul>
<li>
<?php echo display_applications($specs,$_GET['value']); ?>
</li>
</ul>
</div>
</article></td>
</tr>
The RAW print_r($specs) gives you:
Array
(
[poly-soak] => Array
(
[specs] => Array
(
[0] => Array
(
[sku] => 3P-12Y
[diameter] => 3/8"
[tensile] => 3000
[weight] => 3.4
)
[1] => Array
(
[sku] => 3P-14Y
[diameter] => 7/16"
[tensile] => 3380
[weight] => 4.7
)
)
[applications] => Array
(
[0] => Water Rescue
[1] => Canyoneering
)
[benefits] => Array
(
[0] => Lightweight
[1] => Buoyant
[2] => High Visibility
)
)
[poly-soak-economy] => Array
(
[specs] => Array
(
[0] => Array
(
[sku] => FQK-502
[diameter] => 1/8"
[tensile] => 2000
[weight] => 1.5
)
)
[applications] => Array
(
[0] => Water Rescue
)
[benefits] => Array
(
[0] => Economical
[1] => Lightweight
[2] => Buoyant
)
)
[poly-soak-2] => Array
(
[specs] => Array
(
[0] => Array
(
[sku] => 3PN-12Y
[diameter] => 3/8"
[tensile] => 4200
[weight] => 3.05
)
)
[applications] => Array
(
[0] => Water Rescue
[1] => Canyoneering
[2] => Mooring
)
[benefits] => Array
(
[0] => Bright Colors for Greater Visibility
[1] => Supple for Compact Storage
[2] => Certified to the Highest Standard
[3] => Buoyant
)
)
[aqua-d] => Array
(
[specs] => Array
(
[0] => Array
(
[sku] => 3Q-08Y
[diameter] => 1/4"
[tensile] => 3200
[weight] => 1.7
)
[1] => Array
(
[sku] => 3Q-10Y
[diameter] => 5/16"
[tensile] => 3400
[weight] => 2.3
)
[2] => Array
(
[sku] => 3Q-12Y
[diameter] => 3/8"
[tensile] => 4950
[weight] => 3.4
)
)
[applications] => Array
(
[0] => Minimal Water Retention
[1] => Strong & Lightweight
[2] => Buoyant
)
[benefits] => Array
(
[0] => Water Rescue
)
)
)
Related
This question already has answers here:
Pivot a mysql result set and create html table/matrix
(4 answers)
Closed 1 year ago.
I have an array that looks like this:
Array (
Array ( [date] => 04/2021 [name] => Fred [value] => 12.00 )
Array ( [date] => 04/2021 [name] => Tom [value] => 160.00 )
Array ( [date] => 04/2021 [name] => Mike [value] => 9.00 )
Array ( [date] => 07/2021 [name] => Tony [value] => 200.00 )
Array ( [date] => 07/2021 [name] => Fred [value] => 43.00 )
Array ( [date] => 07/2021 [name] => Tom [value] => 114.00 )
Array ( [date] => 07/2021 [name] => Mike [value] => 28.00 )
)
I am trying to get the data into a simple HTML table where the name goes on the x axis, the date on the y axis and the values where they intersect.
For example:
Fred Tom Mike Tony
04/2021 12.00 160.00 9.00 0
07/2021 43.00 114.00 28.00 200.00
I do not know if I am over thinking this but I cannot get this to work - I can get the x axis to work by pulling out the unique values for name but then when it comes to the y axis and the intersections I cannot get the data to display how I need.
I either end up with repetition of columns or a single column and so on. This is where I have gotten up to but still scratching my head how to do this:
<?php
$unique_names = array_unique(array_map(function($elem){
return $elem['name'];
}, $data));
?>
<thead>
<tr>
<th> </th>
<?php foreach ($unique_names as $i) { ?>
<th><?php print $i;?></th>
<?php } ?>
</tr>
</thead>
<tbody>
<?php
foreach ($data as $row) {
for ($i=0; $i<=count($unique_names);$i++) {
if ($i==0) {
print "<tr><td>".$row['date']."<td>";
} else {
print "<td>".$row['value']."<td>";
}
if ($i==count($unique_dates)) {
print "</tr>";
}
}
}
?>
</tbody>
First, reorganize your data into an array that uses the date as key on the first level, and the name on the second. Collect the names at the same time:
$input = [
['date' => '04/2021', 'name' => 'Fred', 'value' => '12.00'],
['date' => '04/2021', 'name' => 'Tom', 'value' => '160.00'],
['date' => '04/2021', 'name' => 'Mike', 'value' => '9.00'],
['date' => '07/2021', 'name' => 'Tony', 'value' => '200.00'],
['date' => '07/2021', 'name' => 'Fred', 'value' => '43.00'],
['date' => '07/2021', 'name' => 'Tom', 'value' => '114.00'],
['date' => '07/2021', 'name' => 'Mike', 'value' => '28.00'],
];
$data = $names = [];
foreach($input as $item) {
$data[$item['date']][$item['name']] = $item['value'];
$names[] = $item['name'];
}
$names = array_unique($names);
Then create your table. Loop over the names to create the header row first.
Then loop over the reorganized data array (to create one row for each date), and inside that loop over your names again - if you find an entry matching the name in the data array, then output the value, otherwise nothing.
<table>
<tr>
<th></th>
<?php foreach($names as $name): ?>
<th><?php echo $name; ?></th>
<?php endforeach; ?>
</tr>
<?php foreach($data as $date => $userData): ?>
<tr>
<td><?php echo $date; ?></td>
<?php foreach($names as $name): ?>
<td><?php echo $userData[$name]??'-'; ?></td>
<?php endforeach; ?>
</tr>
<?php endforeach; ?>
</table>
Result:
<table>
<tr>
<th></th>
<th>Fred</th>
<th>Tom</th>
<th>Mike</th>
<th>Tony</th>
</tr>
<tr>
<td>04/2021</td>
<td>12.00</td>
<td>160.00</td>
<td>9.00</td>
<td>-</td>
</tr>
<tr>
<td>07/2021</td>
<td>43.00</td>
<td>114.00</td>
<td>28.00</td>
<td>200.00</td>
</tr>
</table>
Here is your answer, great exercise.
<html>
<head>
<style>
table, th, td {
border: 1px solid black;
}
</style>
</head>
<body>
<?php
$data = Array (
Array ( 'date' => '04/2021' ,'name' => 'Fred' ,'value' => '12.00' ),
Array ( 'date' => '04/2021' ,'name' => 'Tom' ,'value' => '160.00' ),
Array ( 'date' => '04/2021' ,'name' => 'Mike', 'value' => '9.00' ),
Array ( 'date' => '07/2021' ,'name' => 'Tony' ,'value' => '200.00' ),
Array ( 'date' => '07/2021' ,'name' => 'Fred' ,'value' => '43.00' ),
Array ( 'date' => '07/2021' ,'name' => 'Tom' ,'value' => '114.00' ),
Array ( 'date' => '07/2021' ,'name' => 'Mike' ,'value' => '28.00' )
);
foreach ($data as $key => $value) {
$tmp[$value['name']][$value['date']] = $value;
}
$unique_names = array_unique(array_map(function($elem){
return $elem['name'];
}, $data));
$unique_dates = array_unique(array_map(function($elem){
return $elem['date'];
}, $data));
?>
<table>
<thead>
<tr>
<th>Dates</th>
<?php foreach ($unique_names as $i) { ?>
<th><?php print $i;?></th>
<?php } ?>
</tr>
</thead>
<?php
foreach ($unique_dates as $date)
{
echo "<tr>";
echo "<td>".$date."</td>";
foreach ($unique_names as $name) {
if(array_key_exists($date,$tmp[$name]))
echo "<td>".$tmp[$name][$date]['value']."</td>";
else
echo "<td>0</td>";
}
echo "</tr>";
}
?>
<tbody>
</tbody>
</table>
</body>
</html>
foreach this array result and echo the results
Array
(
[0] => Array
(
[0] => Array
(
[blog_title] => sooraj bloging
[blog_id] => 2
)
[1] => Array
(
[blog_title] => What are Mobile App Testing Challenges?
[blog_id] => 4
)
[2] => Array
(
[blog_title] => sooraj blog
[blog_id] => 8
)
)
[1] => Array
(
[0] => Array
(
[title] => sooraj casestudy
)
)
[2] => Array
(
[0] => Array
(
[career_id] => 14
[title] => Software Engineer .NET sooraj
[location] => Kochi, India.
[description] => Developing .NET applications.
[qualification] => B.Tech. in CSE, MCA
[status] => 0
[created_at] => 2017-11-20 13:14:29
[updated_at] => 0000-00-00 00:00:00
)
)
[3] => Array
(
)
[4] => Array
(
[0] => Array
(
[tst_id] => 146
[tst_name] => John Kasha
[tst_quote] => Gadgeon was extremely professional and was easy to commun sooraj icate and work with on a day-to-day basis. I also liked the fact that they were willing to do the research for specific tasks and present a viable solution or workaround to keep the project on schedule. I would recommend them for any task for any industry software or hardware. Bottom line, they get it done and you get results, not excuses. VP of Engineering.
[tst_desig] => Vice President,Product Development and Engineering
[tst_image] => 91c09ac9ee6234fdfcc523a393800bd5.jpg
[url] =>
[crop_name] => 668959f965ab28815dc97bbc1f8718d8.jpg
[sysDate] => 2017-11-20 15:42:34
)
)
)
Just Run this code
<?php
$array = array(
array(
array(
'blog_title' => 'sooraj bloging',
'blog_id' => 2
),
array(
'blog_title' => 'What are Mobile App Testing Challenges?',
'blog_id' => 4
),
array(
'blog_title' => 'sooraj blog',
'blog_id' => 8
)
),
array(
array(
'title' => 'sooraj casestudy',
)
),
array(
array(
'career_id' => 14,
'title' => 'Software Engineer .NET sooraj',
'location' => 'Kochi, India.',
'description' => 'Developing .NET applications.',
'qualification' => 'B.Tech. in CSE, MCA',
'status' => 0,
'created_at' => '2017-11-20 13:14:29',
'updated_at' => '0000-00-00 00:00:00'
)
),
array(),
array(
array(
'tst_id' => 146,
'tst_name' => 'John Kasha',
'tst_quote' => 'Gadgeon was extremely professional and was easy to commun sooraj icate and work with on a day-to-day basis. I also liked the fact that they were willing to do the research for specific tasks and present a viable solution or workaround to keep the project on schedule. I would recommend them for any task for any industry software or hardware. Bottom line, they get it done and you get results, not excuses. VP of Engineering.',
'tst_desig' => 'Vice President,Product Development and Engineering',
'tst_image' => '91c09ac9ee6234fdfcc523a393800bd5.jpg',
'url' => '',
'crop_name' => '668959f965ab28815dc97bbc1f8718d8.jpg',
'sysDate' => '2017-11-20 15:42:34'
)
)
);
foreach ($array as $value){
foreach ($value as $row){
foreach ($row as $key=> $row1){
echo $key.' - '. $row1;
}
echo '<br>';
}
}
?>
Depending what you're trying to do (debugging vs tabular display), you can "pretty print" the array with var_export like so:
// Assuming your array is $data
echo '<pre>'.var_export($data, TRUE).'</pre>';
Otherwise, to loop through the array as is with a foreach:
// Assuming your array is $data
foreach ($data as $subdata) {
// You probably want to check that this is an array for case #3
if(is_array($subdata)) {
foreach ($subdata as $valueset) {
// Check for array validity (not required for example data, but good to be safe)
if (is_array($valueset)) {
foreach ($subdata as $key => $value) {
// Print each key, value pair as a row
echo $key .' => '.$value . '<br />';
}
}
}
} else {
// Optional handling of empty set
echo 'No data to display...';
}
}
foreach ($array as $value){
foreach ($value as $row){
if (is_array($row)){
foreach ($row as $key => $val){
echo $key."=>". $val."<br>";
}///endForeach
}///endIf
else {
echo $row;
}////endElse
}
}
I have data like this :
[1] => Array
(
[COMPANY_SERVICE_ID] => CS01
[COMPANY_NAME] => HANOMAN SAKTI PRATAMA, PT - JAKARTA
[TARIFF_CURRENCY] => IDR
[SELLING_SERVICE_ID] => SS01
[CONTAINER_TYPE_ID] => DC
[SERVICE_NAME] => CONTAINER TRUCKING SERVICE
[FROM_QTY] => 1
[TO_QTY] => 100
[FROM_NAME] => TANJUNG PRIOK
[FROM_LOCATION_ID] => L096
[TO_NAME] => BALARAJA
[TO_LOCATION_ID] => L002
[RESULT_LOCATION] => Array
(
[L001] => Array
(
[TARIF_20] => 1.500.000,00
[TARIF_40] => 1.750.000,00
[TARIF_45] => 5.500.000,00
[TARIF_4H] => 3.500.000,00
)
[L002] => Array
(
[TARIF_20] => 500.000,00
)
)
)
i wanna unset value of RESULT_LOCATION if value in RESULT_LOCATION different with value of TO_LOCATION_ID.
What should i do?
i try to remove with code like this :
foreach ($hasil_jakarta as $key => $value) {
foreach ($value['RESULT_LOCATION'] as $key1 => $value1) {
if ($value['TO_LOCATION_ID'] != $value['RESULT_LOCATION'][$key1]) {
unset($hasil_jakarta[$key]['RESULT_LOCATION'][$key1]);
}
}
}
but all value of RESULT_LOCATION deleted. Whats wrong with my code?
You don't have to test the value but the key. Then, unset() arrays with different keys.
Here is an example :
<?php
$a = array(
'COMPANY_SERVICE_ID' => 'CS01',
'COMPANY_NAME' => 'HANOMAN SAKTI PRATAMA, PT - JAKARTA',
'TARIFF_CURRENCY' => 'IDR',
'SELLING_SERVICE_ID' => 'SS01',
'CONTAINER_TYPE_ID' => 'DC',
'SERVICE_NAME' => 'CONTAINER TRUCKING SERVICE',
'FROM_QTY' => 1,
'TO_QTY' => 100,
'FROM_NAME' => 'TANJUNG PRIOK',
'FROM_LOCATION_ID' => 'L096',
'TO_NAME' => 'BALARAJA',
'TO_LOCATION_ID' => 'L002',
'RESULT_LOCATION' => array(
'L001' => array(
'TARIF_20' => '1.500.000,00',
'TARIF_40' => '1.750.000,00',
'TARIF_45' => '5.500.000,00',
'TARIF_4H' => '3.500.000,00'
),
'L002' => array(
'TARIF_20' => '500.000,00'
)
)
);
foreach ($a['RESULT_LOCATION'] as $key => $value) {
if ($key != $a['TO_LOCATION_ID']) {
unset($a['RESULT_LOCATION'][$key]);
}
}
The result will be :
php > print_r($a);
Array
(
[COMPANY_SERVICE_ID] => CS01
[COMPANY_NAME] => HANOMAN SAKTI PRATAMA, PT - JAKARTA
[TARIFF_CURRENCY] => IDR
[SELLING_SERVICE_ID] => SS01
[CONTAINER_TYPE_ID] => DC
[SERVICE_NAME] => CONTAINER TRUCKING SERVICE
[FROM_QTY] => 1
[TO_QTY] => 100
[FROM_NAME] => TANJUNG PRIOK
[FROM_LOCATION_ID] => L096
[TO_NAME] => BALARAJA
[TO_LOCATION_ID] => L002
[RESULT_LOCATION] => Array
(
[L002] => Array
(
[TARIF_20] => 500.000,00
)
)
)
Hope it helps.
EDIT
I saw your snippet and adapt the loop for your needs :
foreach ($hasil_jakarta as $h_j_key => $h_j_value) {
foreach ($h_j_value['RESULT_LOCATION'] as $key => $value) {
if ($key != $h_j_value['TO_LOCATION_ID']) {
unset($hasil_jakarta[$h_j_key]['RESULT_LOCATION'][$key]);
}
}
}
Your code was almost good but the unset line was not. In that case, you need to unset a variable from the $hasil_jakarta array.
Good luck !
$list = array(
array(
'header_name' => '1.',
'header_database_name' => '2',
'heading' => 'personal',
),
array(
'header_name' => '11. ',
'header_database_name' => '22',
'heading' => 'professional',
),
array(
'header_name' => '33',
'header_database_name' => '333',
'heading' => 'personal',
),
);
foreach($list as $li)
{
?>
"> ';}
else ($li['heading'] == 'performance')
{echo $li['header_name'].'';}
}
I need to print this array by grouping it by heading for example the one with heading as personal should be displayed under the personal title i.e:
Personal
1
33
Professional
11
my php code is like this
foreach($list as $li)
{
?>
"> ';}
else ($li['heading'] == 'performance')
{echo $li['header_name'].'';}
}
It is printing by group but i also need heading to be added but only one time at the top for example now if i add heading to it it prints as personal 1
professional 2
peronal 3
but i need as
personal
1
2
professional
2
You need to sort array if you want grouping of data, use usort
function headingSort ($x, $y) {
return strcasecmp($x['heading'], $y['heading']);
}
usort($myArray, 'headingSort');
Use like
$new_array = array();
foreach($list as $k=>$v)
{
if(!in_array($v['header_name'], $new_array))
$new_array[$v['heading']][] = $v['header_name'];
else
$new_array[$v['heading']] = $v['header_name'];
}
print_r($new_array);
Try this :
$list = array(
array(
'header_name' => '1.',
'header_database_name' => '2',
'heading' => 'personal',
),
array(
'header_name' => '11. ',
'header_database_name' => '22',
'heading' => 'professional',
),
array(
'header_name' => '33',
'header_database_name' => '333',
'heading' => 'personal',
)
);
$personal = array();
$professional = array();
for($i=0;$i<count($list);$i++){
if($list[$i]['heading']=="professional"){
array_push($professional,$list[$i]);
}else{
array_push($personal,$list[$i]);
}
}
$new = array(
"personal"=>$personal,
"professional"=>$professional
);
echo "<pre>";
print_r($new);
Result will be like :
Array
(
[personal] => Array
(
[0] => Array
(
[header_name] => 1.
[header_database_name] => 2
[heading] => personal
)
[1] => Array
(
[header_name] => 33
[header_database_name] => 333
[heading] => personal
)
)
[professional] => Array
(
[0] => Array
(
[header_name] => 11.
[header_database_name] => 22
[heading] => professional
)
)
)
The solution using array_column(available since PHP 5.5), array_unique, array_keys and implode functions:
$headings = array_column($list, 'heading', 'header_name');
foreach (array_unique($headings) as $v) {
echo ucfirst($v). PHP_EOL;
echo implode("\n", array_keys($headings, $v)). PHP_EOL;
}
The output:
Personal
1
33
Professional
11
As one of the steps toward a greater website redesign I am putting the majority of the content of our website into html files to be used as includes. I am intending on passing a variable to the PHP template page through the URL to call the proper include.
Our website has many programs that each need an index page as well as about 5 sub-pages. These program pages will need a menu system to navigate between the different pages.I am naming the pages pagex_1, pagex_2, pagex_3, etc. where "pagex" is descriptive of the page content.
My question is, what would be the best way to handle this menu system? Is there a way to modify the initial variable used to arrive at the index page to create links in the menu to arrive at the other pages?
Thanks for any help!
I'd store the menu structure in an associative PHP array like so:
$menu = array(
'index'=>array(
'title'=>'Homepage',
'include'=>'home.html',
'subitems'=>array()
),
'products' => array(
'title'=>'Products',
'include'=>'products.html',
'subitems'=>array(
'product1'=>array(
...
),
'product2'=>array(
...
),
'product3'=>array(
...
)
)
)
);
Make that array available to the template script as well (e.g. by include/require). Then use delimiters in the variable to identify the menu item (like a file system does with folders and files) and therefore the resulting page to be included:
'index' would identify the index page
'products' would identifiy the products start page
'products/product1' would identify the product 1 subpage inside the products page
... and so on.
// Menu Array multidimensional
$menu = array(
'index' => array(
'title' => 'Homepage',
'include' => 'home.html',
'subitems' => array()
),
'products' => array(
'title' => 'Products',
'include' => 'products.html',
'subitems' => array(
'product1' => array(
'title' => 'product1',
'include' => 'product1.html',
'subitems' => array(
'product1.2' => array(
'title' => 'product1.2',
'include' => 'product1.2.html',
'subitems' => array()
)
)
),
'product2' => array(
'title' => 'product2',
'include' => 'product2.html',
'subitems' => array()
),
'product3' => array(
'title' => 'product3',
'include' => 'product31.html',
'subitems' => array()
),
'product4' => array(
'title' => 'product4',
'include' => 'product4.html',
'subitems' => array()
)
)
)
);
// Make menu
function makeMenu($menu_array,$is_sub = false,$list=['ul','li']){
$attr = (!$is_sub) ? ' class="menu"' : ' class="submenu"';
$child = NULL;
$menu = "<{$list[0]}{$attr}>";
foreach($menu_array as $id => $items){
foreach($items as $key => $val){
if( is_array($val) ) {
if ( !empty($val) ) $child = makeMenu($val,true,$list);
} else {
$$key = $val;
}
}//foreach
$menu .= "<{$list[1]}>";
$menu .= ''.$title.'';
$menu .= $child; // Sub Menu
$menu .= "</{$list[1]}>";
unset($url, $text, $sub);
}//foreach
$menu .= "</{$list[0]}>";
return $menu;
}
// retrieve the desired page with the shaft
function makeSubMenu($menu, $key) {
return makeMenu(array($menu[$key]));
}
// chain Article
function chainItem(array $array, $unset = '' ){
$ds = array();
if ( is_array($array) )
foreach((array)$unset as $arr) unset($array[$arr]);
foreach($array as $key=>$value)
if (!is_array($value)) $ds[$key] = $value;
return $ds;
}
// Build walk recursive -> single array insert database MySql
function walkRecursive($array, $ordId = true, $unset=[], $children = 'children', $i = 1, $parent = 0, &$res = [] ) {
if ( !is_array($array) ) return array();
foreach(array_values($array) as $key=>$arr) {
$das = array(
'id' => $id = $ordId ? $arr['id'] : $i++,
'parent' => $parent
);
$res[] = array_merge($das,chainItem($arr,$unset));
if( isset($arr[$children]) ) {
walkRecursive($arr[$children], $ordId, $unset, $children, $i, $id, $res );
}
}
return $res;
}
echo makeMenu($menu);
// Result of the print
<ul class="menu">
<li>Homepage</li>
<li>Products
<ul class="submenu">
<li>product1
<ul class="submenu">
<li>product1.2</li>
</ul>
</li>
<li>product2
<ul class="submenu">
<li>product1.2</li>
</ul>
</li>
<li>product3
<ul class="submenu">
<li>product1.2</li>
</ul>
</li>
<li>product4
<ul class="submenu">
<li>product1.2</li>
</ul>
</li>
</ul>
</li>
</ul>
// Build walk recursive -> single array insert database MySql
header("Content-type: text/plain");
print_r( walkRecursive($menu,false,['parent','id'],'subitems') );
// Print array -> Result:
Array
(
[0] => Array
(
[id] => 1
[parent] => 0
[title] => Homepage
[include] => home.html
)
[1] => Array
(
[id] => 2
[parent] => 0
[title] => Products
[include] => products.html
)
[2] => Array
(
[id] => 3
[parent] => 2
[title] => product1
[include] => product1.html
)
[3] => Array
(
[id] => 4
[parent] => 3
[title] => product1.2
[include] => product1.2.html
)
[4] => Array
(
[id] => 4
[parent] => 2
[title] => product2
[include] => product2.html
)
[5] => Array
(
[id] => 5
[parent] => 2
[title] => product3
[include] => product31.html
)
[6] => Array
(
[id] => 6
[parent] => 2
[title] => product4
[include] => product4.html
)
)