i want to replace
[children] => Array
(
)
from my php array...i tried with
$array=str_replace('[children] => Array
(
)',' ',$nestedArray);
print_r($array);
but nothing happened in the array..how should i replace the empty children from php array..
my php output
Array
(
[0] => Array
(
[id] => 44
[name] => அகடம்
[parent] =>
[color] => red
[children] => Array
(
[0] => Array
(
[id] => 45
[name] => மோசடி
[parent] => 44
[color] => red
[children] => Array
(
)
)
[1] => Array
(
[id] => 46
[name] => சூழ்ச்சி
[parent] => 44
[color] => red
[children] => Array
(
)
)
[2] => Array
(
[id] => 47
[name] => அநீதி
[parent] => 44
[color] => red
[children] => Array
(
)
)
[3] => Array
(
[id] => 48
[name] => பொல்லாங்கு
[parent] => 44
[color] => red
[children] => Array
(
)
)
)
)
)
complete php code
<?php
$con=mysqli_connect("localhost","root","pass","data");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$name=$_GET['editor'];
$sql="SELECT * FROM phptab where value LIKE '%".$name."%'";
$r = mysqli_query($con,$sql);
$data = array();
while($row = mysqli_fetch_assoc($r)) {
$data[] = $row;
}
function buildtree($src_arr, $parent_id = 0, $tree = array())
{
foreach($src_arr as $idx => $row)
{
if($row['parent'] == $parent_id)
{
foreach($row as $k => $v)
$tree[$row['id']][$k] = $v;
unset($src_arr[$idx]);
$tree[$row['id']]['children'] = buildtree($src_arr, $row['id']);
}
}
ksort($tree);
return $tree;
}
function insertIntoNestedArray(&$array, $searchItem){
if($searchItem['parent'] == 0){
array_push($array, $searchItem);
return;
}
if(empty($array)){ return; }
array_walk($array, function(&$item, $key, $searchItem){
if($item['id'] == $searchItem['parent']){
array_push($item['children'], $searchItem);
return;
}
insertIntoNestedArray($item['children'], $searchItem);
}, $searchItem);
}
$nestedArray = array();
foreach($data as $itemData){
//$nestedArrayItem['value'] = $itemData['value'];
$nestedArrayItem['id'] = $itemData['id'];
$nestedArrayItem['name'] = $itemData['name'];
$nestedArrayItem['parent'] = $itemData['parent'];
$nestedArrayItem['tooltip'] = $itemData['tooltip'];
$nestedArrayItem['color'] = $itemData['color'];
$nestedArrayItem['level'] = $itemData['level'];
$nestedArrayItem['children'] = array();
//$data[]=$dat;
insertIntoNestedArray($nestedArray, $nestedArrayItem);
}
header('Content-Type: application/json');
print_r( $nestedArray);
?>
expected output
Array
(
[0] => Array
(
[id] => 44
[name] => அகடம்
[parent] =>
[color] => red
[children] => Array
(
[0] => Array
(
[id] => 45
[name] => மோசடி
[parent] => 44
[color] => red
)
[1] => Array
(
[id] => 46
[name] => சூழ்ச்சி
[parent] => 44
[color] => red
)
[2] => Array
(
[id] => 47
[name] => அநீதி
[parent] => 44
[color] => red
)
[3] => Array
(
[id] => 48
[name] => பொல்லாங்கு
[parent] => 44
[color] => red
)
)
)
)
PASTBIN FOR DETAILS - http://pastebin.com/mqyfbdsq
UPDATED CODE BASED ON SUGGESTION - http://pastebin.com/mAkZ4q12
updated php
<?php
$con=mysqli_connect("localhost","root","admin321","data");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$name=$_GET['editor'];
$sql="SELECT * FROM phptab where value LIKE '%".$name."%'";
$i=-1;
$r = mysqli_query($con,$sql);
$data = array();
while($row = mysqli_fetch_assoc($r)) {
if($row['parent']==""){
++$i;
}
foreach($row as $k=>$v){
if($row['parent']==""){
$tree[$i][$k]=$v;
}else{
$tree[$i]['children'][$k]=$v;
}
$data[] = $row;
}
}
function buildtree($src_arr, $parent_id = 0, $tree = array())
{
foreach($src_arr as $idx => $row)
{
if($row['parent'] == $parent_id)
{
foreach($row as $k => $v)
$tree[$row['id']][$k] = $v;
unset($src_arr[$idx]);
$tree[$row['id']]['children'] =
buildtree($src_arr, $row['id']);
}
}
ksort($tree);
return $tree;
}
function insertIntoNestedArray(&$array, $searchItem){
if($searchItem['parent'] == 0){
array_push($array, $searchItem);
return;
}
if(empty($array)){ return; }
array_walk($array, function(&$item, $key, $searchItem){
if($item['id'] == $searchItem['parent']){
array_push($item['children'], $searchItem);
return;
}
insertIntoNestedArray($item['children'], $searchItem);
}, $searchItem);
}
$nestedArray = array();
foreach($data as $itemData){
//$nestedArrayItem['value'] = $itemData['value'];
$nestedArrayItem['id'] = $itemData['id'];
$nestedArrayItem['name'] = $itemData['name'];
$nestedArrayItem['parent'] = $itemData['parent'];
$nestedArrayItem['tooltip'] = $itemData['tooltip'];
$nestedArrayItem['color'] = $itemData['color'];
$nestedArrayItem['level'] = $itemData['level'];
$nestedArrayItem['children'] = array();
//$data[]=$dat;
insertIntoNestedArray($nestedArray, $nestedArrayItem);
}
header('Content-Type: application/json');
$json= json_encode($nestedArray,JSON_UNESCAPED_UNICODE);
echo $json = substr($json, 1, -1);
?>
FINALLY FOUND THE SOLUTION
<?php
$con=mysqli_connect("localhost","root","pass","data");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$name=$_GET['input'];
$sql="SELECT * FROM phptab where value LIKE '%".$name."%'";
$r = mysqli_query($con,$sql);
$data = array();
while($row = mysqli_fetch_assoc($r)) {
$data[] = $row;
}
function buildtree($src_arr, $parent_id = 0, $tree = array())
{
foreach($src_arr as $idx => $row)
{
if($row['parent'] == $parent_id)
{
foreach($row as $k => $v)
$tree[$row['id']][$k] = $v;
unset($src_arr[$idx]);
$tree[$row['id']]['children'] = buildtree($src_arr, $row['id']);
}
}
ksort($tree);
return $tree;
}
function insertIntoNestedArray(&$array, $searchItem){
if($searchItem['parent'] == 0){
array_push($array, $searchItem);
return;
}
if(empty($array)){ return; }
array_walk($array, function(&$item, $key, $searchItem){
if($item['id'] == $searchItem['parent']){
array_push($item['children'], $searchItem);
return;
}
insertIntoNestedArray($item['children'], $searchItem);
}, $searchItem);
}
$nestedArray = array();
function array_remove_empty($haystack)
{
foreach ($haystack as $key => $value) {
if (is_array($value)) {
$haystack[$key] = array_remove_empty($haystack[$key]);
}
if (empty($haystack[$key])) {
unset($haystack[$key]);
}
}
return $haystack;
}
foreach($data as $itemData){
$nestedArrayItem['id'] = $itemData['id'];
$nestedArrayItem['name'] = $itemData['name'];
$nestedArrayItem['parent'] = $itemData['parent'];
$nestedArrayItem['tooltip'] = $itemData['tooltip'];
$nestedArrayItem['color'] = $itemData['color'];
$nestedArrayItem['level'] = $itemData['level'];
$nestedArrayItem['children'] = array();
insertIntoNestedArray($nestedArray, $nestedArrayItem);
}
header('Content-Type: application/json');
$jj=(array_remove_empty($nestedArray));
$json=json_encode($jj,JSON_UNESCAPED_UNICODE);
echo $json;
?>
Thank you for editing your question.
The best course of action is to avoid multiple loops over the same array just to add/remove elements. D.R.Y. - Don't Repeat Yourself
If you don't want to have certain elements in your array, don't ever put them in.
If you want a specific array structure, build it appropriately, one time.
I haven't tested this, but it should provide you with the desired array structure and values while using just one loop. If not, please edit your question to explain, send me a comment, and I'll assist further.
$name=$_GET['editor'];
// $_GET must be validated/santized before used in query...
$sql="SELECT * FROM phptab where value LIKE '%".$name."%' ORDER BY `parent`,`id`";
$r=mysqli_query($con,$sql);
$i=-1;
$j=-1;
while($row=mysqli_fetch_assoc($r)){
if($row['parent']=="0"){
++$i; // if a parent row, increment its numeric key
}else{
++$j; // if a child row, increment its numeric key
}
foreach($row as $k=>$v){
if($row['parent']=="0"){
// parent row data goes in outer array
$tree[$i][$k]=$v;
}else{
// child row parent's children (inner) array with its numeric key
$tree[$i]['children'][$j][$k]=$v;
}
}
}
header('Content-Type: application/json');
$json=json_encode($tree,JSON_UNESCAPED_UNICODE);
echo $json=substr($json,1,-1);
Related
I have a JSON populated output.
Wherever the children are not available the children index is missing.
[7] => Array
(
[id] => 171
[text] => Some Text
[groupid] => 170
[leaf] => false
[qtip] => Cool
)
However, I need the children to be added with an empty array.
[7] => Array
(
[id] => 171
[text] => Some Text
[groupid] => 170
[leaf] => false
[qtip] => Cool
[children] => []
)
Here is my code that creates the output:
$res = $dbConn->prepare($sql);
$res->execute();
$result = $res->fetchAll(PDO::FETCH_ASSOC);
$tmpData = false;
foreach ($result as $k => &$val) {
$tmpData[$val['id']] = &$val;
}
foreach ($result as $k => &$val) {
if ($val['groupid'] && isset($tmpData[$val['groupid']])) {
$tmpData[$val['groupid']]['children'][] = &$val;
}
}
foreach ($result as $k => &$val) {
if ($val['groupid'] && isset($tmpData[$val['groupid']])) {
unset($result[$k]);
}
}
$res->execute();
$result = $res->fetchAll(PDO::FETCH_ASSOC);
$tmpData = false;
foreach ($result as $k => &$val) {
$tmpData[$val['id']] = &$val;
}
foreach ($result as $k => &$val) {
if ($val['groupid'] && isset($tmpData[$val['groupid']])) {
$tmpData[$val['groupid']]['children'][] = &$val;
} else {
$tmpData[$val['groupid']]['children'] = [];
}
}
foreach ($result as $k => &$val) {
if ($val['groupid'] && isset($tmpData[$val['groupid']])) {
unset($result[$k]);
}
}
By the way the idea is "play" with exists or not the $val.
Can you help me refactor this block of code? I'm quite having a hard time to decide how can I refactor nested for each loop or not use foreach loop at all.
$matcherResults = [];
foreach ($resultItems as $reqId => $resultItem) {
if (empty($resultItem)) {
continue;
}
foreach ($resultItem as $reg => $data) {
if (empty($data)) {
continue;
}
foreach ($data as $regs => $regData) {
if (empty($regData)) {
continue;
}
$matcherResult = new MatcherResult(
$regData,
null,
$reg,
$reqId
);
array_push($matcherResults, $matcherResult);
}
}
}
I've tried doing this but unable to come up with the MatcherResult object.
foreach ($resultItems as $reqId => $resultItem) {
$resultItem = array_filter($resultItem, function($resultItem) {
if(!empty($resultItem)) {
return true;
}
});
}
foreach ($resultItem as $regs => $value) {
$matcherResults = array_filter($value, function($value) {
return !empty($value);
});
}
EDIT:
As requested.
Here is a sample of resultItems.
Array
(
[3] => Array
(
[test1] => Array
(
[0] => Array
(
[database] => test1
[active] => 1
[reg] => test1
[full_name] => fname1 lname1
[image_url] => image.png
[last_name] => lname1
[first_name] => fname1
)
)
)
)
Is it possible that one of the lower levels could be a null instead of an empty array? If empty is just checking for an empty array, you could do this:
$matcherResults = [];
foreach ($resultItems as $reqId => $resultItem) {
foreach ($resultItem as $reg => $data) {
foreach ($data as $regs => $regData) {
if (!empty($regData)) {
$matcherResult = new MatcherResult(
$regData,
null,
$reg,
$reqId
);
array_push($matcherResults, $matcherResult);
}
}
}
}
I have an array (From mysql),
Array (
[0] => Array (
[heading] => Page Name change
[name] => Page_Name_change
[menu] => online
)
[1] => Array (
[heading] => Lorem ipsum dolor
[name] => Lorem_ipsum_dolor_
[menu] => akshaya
)
[2] => Array (
[heading] => fgdfgfdgdfgdf
[name] => fgdfgfdgdfgdf
[menu] => akshaya
)
)
I need to split it into separate arrays, basis on [menu], check this php
function getpage() {
$query = "SELECT heading,name,menu FROM pages";
$res = $this->_conn->query($query);
while ($row = mysqli_fetch_assoc($res)) {
$result[] = $row;
}
for ($i=0; $i < count($result); $i++) {
if (strcmp($result[$i]['menu'],'akshaya') == 0) {
for ($j=0; $j < count($result[$i]) ; $j++)
$menu = $result[$i][$j];
}
}
//if(strcmp($row['menu'],'akshaya')==0) { }
return $menu;
}
The expected result is the array where each menu segment has the list of the elements from the initial array, like that:
[
'online' => [
[
'heading' => '...',
'name' => '...',
],
],
'akshaya' => [
[...],
[...],
],
]
its for display an Navigation Menu & Submenu,
function getpage() {
$query = "SELECT heading,name,menu FROM pages";
$res = $this->_conn->query($query);
while ($row = mysqli_fetch_assoc($res)) {
$result[] = $row;
}
$menu = [];
foreach ($result as $menuItem) {
$menu[$menuItem['menu']][] = $menuItem;
}
return $menu;
}
function getpage() {
$query = "SELECT heading,name,menu FROM pages";
$res = $this->_conn->query($query);
while ($row = mysqli_fetch_assoc($res)) {
$result[] = $row;
}
$menu = [];
foreach ($result as $menuItem) {
$menu[$menuItem['menu']][] = $menuItem;
}
return $menu;
}
<?php
$nav=new Pages();
$res=$nav->getpage();
//print_r($res);
echo "<br>";
foreach ($res as $r){
// print_r($r);
echo "<br>";
foreach($r as $rc){
if (strcmp($rc['menu'],'akshaya') == 0) {
$akshaya[]=$rc;
}
echo "<br>";
}
}
print_r($akshaya);
echo count($res);
?>
OutPut:
Array ( [0] => Array ( [heading] => Lorem ipsum dolor [name] => Lorem_ipsum_dolor_ [menu] => akshaya ) [1] => Array ( [heading] => fgdfgfdgdfgdf [name] => fgdfgfdgdfgdf [menu] => akshaya ) )
I will use this function in this loop :
while ($nbrDocument < 12 && $nbrTags > 0)
{
$tmpDocuments = $this
->get('fos_elastica.manager')
->getRepository('AppBundle:Document')
->findFromTag();
$tagPossibilities = $this->generateTagPossibilities($userTags, $nbrTags);
foreach ($tmpDocuments as $document)
{
$present = true;
foreach ($tagPossibilities as $tags)
{
foreach ($tags as $tag)
{
if (!in_array($tag, $document->getTag()))
{
$present = false;
break;
}
}
if ($present) {
break;
}
}
$nbrDocument ++;
array_push($documents, $$document);
}
$nbrTags--;
}
And I need to create the method generateTagPossibilities.
The first parameter contains an array of string data, and the second is the size
of the possibilities I need to have.
For exemple, if I have [1][2][3][4] in my array and $nbrTag = 4, this function should return [1][2][3][4], if $nbrTag = 3, it should return [[1][2][3]] [[1][3][4]] [[2][3][4]] ...
Got any idea of how I can do that ?
You can use the following functions :
function array_hash($a)
{
$s = '';
foreach($a as $v)
{
$s.=$v.'-';
}
return hash('sha256',$s);
}
function removeOne($setList)
{
$returnSetList = array();
$hashList = array();
foreach($setList as $set)
{
foreach($set as $k=>$v)
{
$tmpSet = $set;
unset($tmpSet[$k]);
$hash = array_hash($tmpSet);
if(!in_array($hash, $hashList))
{
$returnSetList[] = $tmpSet;
$hashList[] = $hash;
}
}
}
return $returnSetList;
}
function generateTagPossibilities($userTags, $nbrTags)
{
$aUserTags = array($userTags);
$cUserTags = count($userTags);
if($nbrTags==$cUserTags)
return $aUserTags;
for($i=0; $i<($cUserTags-$nbrTags); $i++)
$aUserTags = removeOne($aUserTags);
return $aUserTags;
}
// Example !
$a = array(1,2,3,4);
print_r(generateTagPossibilities($a,2));
/*
Array
(
[0] => Array
(
[2] => 3
[3] => 4
)
[1] => Array
(
[1] => 2
[3] => 4
)
[2] => Array
(
[1] => 2
[2] => 3
)
[3] => Array
(
[0] => 1
[3] => 4
)
[4] => Array
(
[0] => 1
[2] => 3
)
[5] => Array
(
[0] => 1
[1] => 2
)
)
*/
I'm trying to group airlines with relations into single chains.
Array
(
[0] => Array
(
[0] => Aeroflot
[1] => S7
[2] => Transaero
)
[1] => Array
(
[0] => Alitalia
[1] => Lufthansa
)
[2] => Array
(
[0] => Transaero
[1] => United
)
[3] => Array
(
[0] => United
[1] => Alitalia
)
[4] => Array
(
[0] => Volotea
[1] => Iberia
)
[5] => Array
(
[0] => Transaero
[1] => Aeroflot
)
)
From that array I need to find connections between elements and combine it to groups. Expected results:
Array
(
[0] => Array
(
[0] => Aeroflot
[1] => S7
[2] => Transaero
[3] => United
[4] => Alitalia
[5] => Lufthansa
)
[1] => Array
(
[0] => Volotea
[1] => Iberia
)
)
Can anyone help with that? I've tried a dozen of ways but still get no success.
The most closest way I've tried which works but not in all cases:
function array_searchRecursive($needle,$haystack) {
foreach($haystack as $key=>$value) {
$current_key=$key;
if($needle===$value OR (is_array($value) && array_searchRecursive($needle,$value) !== false)) {
return $current_key;
}
}
return false;
}
foreach ($newarr as $key => $airlines)
{
foreach ($airlines as $lastkey => $airline)
{
$index = array_searchRecursive($airline,$newarr);
echo $airline.$index."\n";
if ($index !== false)
{
$newarr[$index] = array_merge($newarr[$index],$airlines);
$lastarr[] = $index;
}
}
}
But it doesn't match all values in array.
Recursive function will help you. You are welcome )
$arr = array(
array('Aeroflot','S7','Transaero'),
array('Alitalia','Lufthansa'),
array('Transaero','United'),
array('United','Alitalia'),
array('Volotea','Iberia'),
array('Transaero','Aeroflot')
);
function getConnections($arr,$curr_line_n=0,$num=0) {
for($i=0;$i<count($arr[$curr_line_n]);$i++) {
$cur_air_name = $arr[$curr_line_n][$i];
for($k=$curr_line_n+1; $k<count($arr); $k++) {
for($l=0;$l<count($arr[$k]);$l++) {
if ($arr[$k][$l]==$cur_air_name) {
$arr[$curr_line_n] = array_values(array_unique(array_merge($arr[$curr_line_n],$arr[$k])));
array_splice($arr,$k,1);
$num++;
$arr = getConnections($arr,$curr_line_n,$num);
}
}
}
}
$num++;
$curr_line_n++;
if ($curr_line_n!=count($arr)) {
$arr = getConnections($arr,$curr_line_n,$num);
}
return $arr;
}
print_r(getConnections($arr));
As per your example you are just grouping sub arrays by taking first sub array as reference. for example if you have any elements common in first sub array and in subsequent sub arrays then you combine them into one sub array.
<?php
$arr = array(
array('a', 'b', 'c', 'd'),
array('d', 't'),
array('t', 'f'),
array('k', 'o'),
array('p', 'z')
);
$arr_implode = array();
foreach ($arr as $key => $value) {
if (is_array($value)) {
$arr_implode[$key] = implode('', $value);
} else {
$arr_implode[$key] = $value;
}
}
$arr_key = array();
$result = array();
$count = count($arr_implode);
$tempj = 0;
for ($i = 0; $i <= $count; $i++) {
$flag = FALSE;
for ($j = ($i + 1); $j < $count; $j++) {
similar_text($arr_implode[$i], $arr_implode[$j], $percent);
if ($percent > 0) {
$result[] = array_merge($arr[$i],$arr[$j]);
break;
} else {
$result[] = $arr[$j];
break;
}
}
}
foreach($result as $key => $val){
$result[$key] = array_unique($val);
}
echo "<pre>";
print_r($result);
echo "</pre>";
?>
Try this code.
$arr = [
['Aeroflot', 'S7', 'Transaero'],
['Alitalia', 'Lufthansa'],
['Transaero', 'United'],
['United', 'Alitalia'],
['Volotea', 'Iberia'],
['Transaero', 'Aeroflot']
];
$hash = [];
$result = [];
foreach($arr as $set){
foreach($set as $el){
if(!$hash[$el]) $hash[$el] = [] ;
$hash[$el] = array_merge($hash[$el], $set);
}
}
function merge_connections(&$h, $key){
if(!$h[$key]) return [];
$data = [$key];
$rels = $h[$key];
unset($h[$key]);
foreach($rels as $rel){
if($rel==$key) continue;
$data = array_merge($data, merge_connections($h, $rel));
}
return $data;
}
foreach(array_keys($hash) as $company){
if(!$hash[$company]) continue;
array_push($result, merge_connections($hash, $company));
}
print_r($result);