Any ideas on how can I generate a nested list without the need to recreate a lot of select statements?
I'm currently using this code
<ol>
<?php
$getparents=mysql_query("select id,subject from list");
while($parent=mysql_fetch_assoc($getparents)){
?>
<li><?php echo $parent["id"];?></li>
<?php
$childsparent=$parent["id"];
$getchild=mysql_query("select id,subject from list where parent_id='".$childsparent."'");
if (!mysql_num_rows($getchild){
echo '</ol>';
}
else
{
echo '<ol>';
while ($child=mysql_fetch_assoc($getchild)){
echo '<li>'.$child["subject"].'</li>';
}
$childsparent=$child["id"];
}
?>
</ol>
Is there a way to stop the while from getting all results and check a result first if it has child nests before it moves forward?
The result should be something like
1.
2.
2.1
2.1.1
2.2
3
I found this function I wrote some time ago. I think it is the kind of thing you want. You just need to change the logic to print out rather than store to an array:
function nestify( $arrs, $depth_key = 'depth' )
{
$nested = array();
$depths = array();
foreach( $arrs as $key => $arr ) {
if( $arr[$depth_key] == 0 ) {
$nested[$key] = $arr;
$depths[$arr[$depth_key] + 1] = $key;
}
else {
$parent =& $nested;
for( $i = 1; $i <= ( $arr[$depth_key] ); $i++ ) {
$parent =& $parent[$depths[$i]];
}
$parent[$key] = $arr;
$depths[$arr[$depth_key] + 1] = $key;
}
}
return $nested;
}
$arr = array(
array( 'name' => 'Joe Splogs', 'depth' => 0 ),
array( 'name' => 'ProSplogger', 'depth' => 0 ),
array( 'name' => 'Pinky Lyres', 'depth' => 1 ),
array( 'name' => 'Pseudologia fantastica', 'depth' => 2 ),
array( 'name' => 'TextLinkBarry', 'depth' => 1 ),
array( 'name' => 'Foo bar Jones', 'depth' => 0 )
);
$new = nestify( $arr, 'depth' );
#-> Returns
array (
'0' => array
(
'name' => 'Joe Splogs',
'depth' => 0
),
'1' => array
(
'name' => 'ProSplogger',
'depth' => 0
'2' => array
(
'name' => 'Pinky Lyres',
'depth' => 1
'3' => array
(
'name' => 'Pseudologia fantastica',
'depth' => 2
),
),
'4' => array
(
'name' => 'TextLinkBarry',
'depth' => 1
),
),
'5' => array
(
'name' => 'Foo bar Jones',
'depth' => 0
),
);
Related
I will try to explain everything :)
I have 2 arrays:
$packs = array(
array(
'name' => 'Pack 1',
'zones' => array(
array('zone' => 2),
array('zone' => 2),
)
),
array(
'name' => 'Pack 2',
'zones' => array(
array('zone' => 2),
array('zone' => 2),
array('zone' => 2),
)
),
array(
'name' => 'Pack 3',
'zones' => array(
array('zone' => 2),
array('zone' => 3),
)
),
array(
'name' => 'Pack 4',
'zones' => array(
array('zone' => 3),
array('zone' => 3),
)
)
);And products:
$products = array(
array(
'id' => '1',
'zone' => '2'
),
array(
'id' => '8',
'zone' => '2'
),
array(
'id' => '13',
'zone' => '3'
),
array(
'id' => '11',
'zone' => '2'
),
array(
'id' => '10',
'zone' => '2'
),
array(
'id' => '12',
'zone' => '3'
)
);
Then I would like to have all $packs zones combination with those products zones.
For example, products_zones are 2, 2, 3, 2, 2, 3 then I would like something like this:
Packs:
Combination 1:
Pack 1 (when Pack zones are in Products Zones, add pack to combination and remove products from array)
Pack 1
Combination 2:
Pack 1
Pack 3
Combination 3:
Pack 1
Pack 4
Combination 4:
Pack 2
Pack 4
Combination 5:
Pack 2
Pack 2
Pack 4
I'm trying to do that with recursive function but doesn't work. I leave here a link with code:
function search_recursive( $packs = array(), $products = array(), $packs_in = array(), $pass = null ) {
foreach ($packs as $index => $pack) {
// Get zones to compare
$arr_zones = array_column($pack['zonas'], 'zona');
$products_zones = array_column($products, 'zone');
// Check if pack zones are in product zones
$cheak_arr = [];
$arr_zones_temp = $arr_zones;
foreach ($products_zones as $index2 => $temp_zone) {
if ( in_array($temp_zone, $arr_zones_temp) ) {
$cheak_arr[] = $temp_zone;
foreach ($arr_zones_temp as $key => $value) {
if ( $value == $temp_zone ) {
unset($arr_zones_temp[$key]);
break;
}
}
}
}
if ( count($arr_zones) == count($cheak_arr) ) {
// I create a index for first time
$custom_index = ($pass == null) ? $index : $pass;
// Add pack to array if pack zones are in product zones
if ( !isset($packs_in[$custom_index]) ) {
$packs_in[$custom_index] = [
'packs' => array($pack)
];
}
else {
$packs_in[$custom_index]['packs'][] = $pack;
}
// Remove products that have zones same in pack
$temp_prod = $products;
foreach ($arr_zones as $zone) {
foreach ($temp_prod as $key => $value) {
if ( $value['zone'] == $zone ) {
unset($temp_prod[$key]);
break;
}
}
}
if ( $pass != null ) {
$products = $temp_prod;
}
if ( !empty($temp_prod) ) {
// Call myself with less products and index defined
$packs_in = search_recursive( $packs, $temp_prod, $packs_in, $custom_index );
}
else if ( $pass != null ) {
break;
}
}
}
return $packs_in;
}
I think I got what you need, but I'm still a bit confused. Anyway, I suggest you to simplify you "packs" array like my code below:
<?php
$packs = array(
array(
'name' => 'Pack 1',
'zones' => array(2,2),
),
array(
'name' => 'Pack 2',
'zones' => array(2,2,2),
),
array(
'name' => 'Pack 3',
'zones' => array(2,3),
),
array(
'name' => 'Pack 4',
'zones' => array(3,3),
)
);
$products = array(
array(
'id' => '8',
'zone' => '2'
),
array(
'id' => '13',
'zone' => '3'
),
array(
'id' => '11',
'zone' => '2'
),
array(
'id' => '10',
'zone' => '2'
),
array(
'id' => '12',
'zone' => '3'
)
);
$product_zones = array_column($products, 'zone');
//let's order an change to a sequence of numbers like 22233
sort($product_zones);
$product_zones = join('', $product_zones);
$combinations = [];
//here we iterate through all packs 1->2,3,4; 2->3,4 3->4 to find if it matches
foreach($packs as $k => $pack) {
// use k+1 if you can't match the pack with itself
for ($i = $k, $c = count ($packs); $i < $c; $i++) {
//here we do the same as before to combine the packs as string, ex.: 2223
$pack_zones = array_merge($pack['zones'], $packs[$i]['zones']);
sort($pack_zones);
$pack_zones = join('', $pack_zones);
//if it's a substring of our product zones then we have a valid combination
if (strpos($product_zones, $pack_zones) !== false) {
$combinations[] = [$pack['name'], $packs[$i]['name']];
}
}
}
print_r($combinations);
result: 1,3 (22223) ; 1,4 (2233) ; 2,4 (22233) ; 3,3 (2233)
I have an array of data like this . This array is the result of a database query , I want to get the index of rows and columns . I tried to get the index of each row but nonetheless failed. so, can anyone help me?
Query Result
array(
(int) 0 => array(
'B' => array(
'company' => 'ABC'
),
'User' => array(
'company' => 'abc'
),
(int) 0 => array(
'date_part' => '3',
'jumlah' => null,
'jumbuy' => '50990',
'admin' => '50010'
),
(int) 1 => array(
'date_part' => '4',
'jumlah' => null,
'jumbuy' => '98990',
'admin' => '2010'
)
),
(int) 1 => array(
'B' => array(
'company' => 'BCD'
),
'User' => array(
'company' => 'bcd'
),
(int) 0 => array(
'date_part' => '3',
'jumlah' => null,
'jumbuy' => '65000',
'admin' => '5000'
),
(int) 1 => array(
'date_part' => '4',
'jumlah' => null,
'jumbuy' => '9000',
'admin' => '5000'
)
),
(int) 3 => array(
'B' => array(
'company' => 'CDE'
),
'User' => array(
'company' => 'cde'
),
(int) 0 => array(
'date_part' => '4',
'jumlah' => null,
'jumbuy' => '34566',
'admin' => '2010'
)
)
);
Get Index
for ($row = 0; $row < count($array); $row++) {
for($col = 0; $col < count(.....); $col++ ) {
echo "Baris [row] kolom [colum]"; // output row and column
}
}
The below code will give you all the indexes of this given array.
I checked the given array with the following code in my localhost.
And it gives us all the keys and the values in this array.
Try this
<?php
foreach($array as $arr=>$value )
{
foreach($value as $ar=>$a)
{
echo $ar."<br>";
foreach($a as $res =>$r)
{
echo $res.": ";
echo $r;
echo "<br>";
}
}
}
?>
Use nested foreach for echoes keys:
foreach ($array as $row => $v) {
foreach ($v as $col => $val) {
echo 'row: ' . $row . ', col: ' . $col . '<br>';
}
}
use the following
foreach ($values as $inde => $value) {
foreach ($value as $key => $result) {
echo '['. $inde.'] ---' .$key . '<br>';
}
}
output will be
[0] ---B
[0] ---User
[0] ---0
[0] ---1
[1] ---B
[1] ---User
[1] ---0
[1] ---1
[3] ---B
[3] ---User
[3] ---0
I have this php array X.
X= array(
'Parent' => array(
'title' => '123',
)
)
I have this php array Y.
Y = array(
'Parent' => array(
'id' => '16',
'title' => 'T1',
),
'Children' => array(
(int) 0 => array(
'id' => '8',
'serial_no' => '1',
),
(int) 1 => array(
'id' => '9',
'serial_no' => '2',
),
(int) 2 => array(
'id' => '14',
'serial_no' => '6',
)
)
)
I want to copy the Children of array Y to the parent of array X to form array Z such that it looks like this;
Z= array(
'Parent' => array(
'title' => '123',
)
'Children' => array(
(int) 0 => array(
'serial_no' => '1'
),
(int) 1 => array(
'serial_no' => '2'
),
(int) 2 => array(
'serial_no' => '6'
)
)
)
Please note that the id key-value pair was removed from the Children of array Y.
I wrote some code of my own.
$Z = array();
$i=0;
foreach($Y as $temp)
{
$Z['Children'][$i] = $temp['Children'][$i];
unset($Z['Children'][$i]['id'];
$i++;
}
$Z['Parent']=$temp['Parent'];
Unfortunately, there is an undefined index error. How can this be done in php? Forget about my code if there are better approaches.
Actually your approach works too, but you need to iterate over sub-array:
$Z = array();
$i=0;
foreach($Y['Children'] as $temp)
{
$Z['Children'][$i] = $temp;
unset($Z['Children'][$i]['id'];
$i++;
}
or what I may do:
$Z = $X;
$Z['Children'] = array();
foreach ( $Y['Children'] as $child ) {
$Z['Children'][] = array(
'serial_no' => $child['serial_no'],
);
}
You can do like.
$Z = array();
foreach($Y['Children'] as $temp)
{
$Z['Children'][] = array('serial_no' => $temp['serial_no']);
}
$Z['Parent']=$X['Parent'];
I have this php associative array which I created from a MySQL query. It looks like this;
array(
(int) 0 => array(
'items' => array(
'index_no' => '1'
),
(int) 0 => array(
'NumItems' => '2'
)
),
(int) 1 => array(
'items' => array(
'index_no' => '2'
),
(int) 0 => array(
'NumItems' => '3'
)
)
It looks unnecessarily complicated. I would like to simplify it to look something like this;
array(
(int) 0 => array(
'index_no' => '1',
'NumItems' => '2'
)
),
(int) 1 => array(
'index_no' => '2',
'NumItems' => '3'
)
)
How can this be done in php? I have been stuck on this problem for some time. I will post my answer if I have it. I would appreciate it if someone could give me some starting point. Thank you very much.
You can try this out:
$tempArray = array(
(int) 0 => array(
'items' => array(
'index_no' => '1'
),
(int) 0 => array(
'NumItems' => '2'
)
),
(int) 1 => array(
'items' => array(
'index_no' => '2'
),
(int) 0 => array(
'NumItems' => '3'
)
));
$newArray = array();
$i=0;
foreach($tempArray as $temp) {
$newArray[$i]['index_no'] = $temp['items']['index_no'];
$newArray[$i]['NumItems'] = $temp[0]['NumItems'];
$i++;
}
print "<pre>";
print_r($newArray);
try this
<?php $res=array(array('item'=>1,'number'=>5),array('item'=>2,'number'=>56));
$final_array =array();
$i=0;
foreach ($res as $val)
{
foreach($val as $key=>$val2)
{
$final_array[$i][$key] = $val2;
}$i++;
}
print_r($final_array);
?>
Here is solution for you.
$diffArray = array(
(int) 0 => array(
'items' => array(
'index_no' => '1'
),
(int) 0 => array(
'NumItems' => '2'
)
),
(int) 1 => array(
'items' => array(
'index_no' => '2'
),
(int) 0 => array(
'NumItems' => '3'
)
));
print_r($diffArray);
$getArray = array();
foreach ($diffArray as $simArray) {
$getArray['index_no'][] = $simArray['items']['index_no'];
$getArray['NumItems'][]= $simArray[0]['NumItems'];
}
print_r($getArray);
$newArray = array();
foreach ($array as $items) {
$temp = array('index_no' => $items['index_no']);
$temp = array_merge($temp, $items[0]);
$newArray[] = $temp;
}
it will add all the keys to the array under index - 0
I have an array with tree data (by parent id). I want to convert it to multidimensional array. What is the best way to achieve that? Is there any short function for that?
Source array:
$source = array(
'0' => array(
'Menu' => array(
'id' => 45
'name' => 'Home'
'parent_id' => 1
)
)
'1' => array(
'Menu' => array(
'id' => 47
'name' => 'Get started'
'parent_id' => 1
)
)
'2' => array(
'Menu' => array(
'id' => 72
'name' => 'Attributes'
'parent_id' => 71
)
)
'3' => array(
'Menu' => array(
'id' => 73
'name' => 'Headings'
'parent_id' => 71
)
)
'4' => array(
'Menu' => array(
'id' => 75
'name' => 'Links'
'parent_id' => 71
)
)
'5' => array(
'Menu' => array(
'id' => 59
'name' => 'Images'
'parent_id' => 75
)
)
'6' => array(
'Menu' => array(
'id' => 65
'name' => 'Lists'
'parent_id' => 75
)
)
);
Some parents are missing from the source array. I would like the items with missing parent to be root. Result array:
$result = array(
'0' => array(
'Menu' => array(
'id' => 45
'name' => 'Home'
'parent_id' => 1
)
'Children' => array()
)
'1' => array(
'Menu' => array(
'id' => 47
'name' => 'Get started'
'parent_id' => 1
)
'Children' => array()
)
'2' => array(
'Menu' => array(
'id' => 72
'name' => 'Attributes'
'parent_id' => 71
)
'Children' => array()
)
'3' => array(
'Menu' => array(
'id' => 73
'name' => 'Headings'
'parent_id' => 71
)
'Children' => array()
)
'4' => array(
'Menu' => array(
'id' => 75
'name' => 'Links'
'parent_id' => 71
)
'Children' => array(
'0' => array(
'Menu' => array(
'id' => 59
'name' => 'Images'
'parent_id' => 75
)
'Children' => array()
)
'1' => array(
'Menu' => array(
'id' => 65
'name' => 'Lists'
'parent_id' => 75
)
'Children' => array()
)
)
)
);
Update: removed square brackets.
I don't think there is a built-in function in PHP that does this.
I tried the following code, and it seems to work to prepare the nested array the way you describe:
$nodes = array();
$tree = array();
foreach ($source as &$node) {
$node["Children"] = array();
$id = $node["Menu"]["id"];
$parent_id = $node["Menu"]["parent_id"];
$nodes[$id] =& $node;
if (array_key_exists($parent_id, $nodes)) {
$nodes[$parent_id]["Children"][] =& $node;
} else {
$tree[] =& $node;
}
}
var_dump($tree);
I wrote a similar algorithm in a PHP class I wrote for my presentation Hierarchical Models in SQL and PHP, but I was using objects instead of plain arrays.
I wrote this variant considering root parent_id is 0 or missing. No matter children after parents in DB ($source) or not.
$source_by_id = array();
foreach ($source as &$row){
$source_by_id[$row['id']] = &$row;
}
foreach ($source_by_id as $id => &$row){
$source_by_id[ intval($row['parent_id']) ]['children'][$id] = &$row;
}
// remove cycling itself
unset($source_by_id[0]['children'][0]);
$result = $source_by_id[0]['children'];
Result array keys are appropriate ids. Enjoy!
I was looking for an example of how to do this, with categories. This example assumes that parents will always have a parent id of '0'. The example is using ZF2.
No references, or recursion. The trick is in the output, you look for the [0] index, and for the children, you specify the parent_id as the index.
$categoryLookup = $this->getCategoryLookup($associateById=true);
if ($assignedCategories) {
$categoryHeirarchy = array();
foreach($assignedCategories as $assignedCategory) {
$child = $categoryLookup[$assignedCategory->category_id];
$parent = $categoryLookup[$child->parent_id];
$categoryHeirarchy[$child->parent_id][] = $categoryLookup[$child->category_id];
$categoryHeirarchy[$parent->parent_id][$parent->category_id] = $categoryLookup[$parent->category_id];
}
return $categoryHeirarchy;
}
<h3>Categories</h3>
<dl class="dl-horizontal">
<?php foreach($this->categoryHeirarchy[0] as $parent): ?>
<dt><?php echo $this->escapeHtml($parent->name); ?></dt>
<?php foreach($this->categoryHeirarchy[$parent->category_id] as $child): ?>
<dd><?php echo $this->escapeHtml($child->name); ?></dd>
<?php endforeach; ?>
<?php endforeach; ?>
</dl>