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.
Related
I have multidimensional array as follows,
[0] => Array
(
[data] =>
[id] => 0000
[name] => Swirl
[categories] => Array
(
[0] => Array
(
[id] => 0001
[name] => Whirl
[products] => Array
(
[0] => Array
(
[id] => 0002
[filename] => 1.jpg
)
[1] => Array
(
[id] => 0003
[filename] => 2.jpg
)
)
)
)
)
I have used the following function to find keys.
function find_parent($array, $needle, $parent = null) {
foreach ($array as $key => $value) {
if (is_array($value)) {
$pass = $parent;
if (is_string($key)) {
$pass = $key;
}
$found = find_parent($value, $needle, $pass);
if ($found !== false) {
return $found;
}
} else if ($key === $needle) {
return $parent;
}
}
return false;
}
$parentkey = find_parent($array, 'id');
Now i need to unset the products array and replace it with another array.
how to do this.please help.
Thanks,
sarnitha
You can use a recursive function over an array:
function replaceInArray(array &$arr, $needleKey, array $replacement) {
foreach ($arr as $k => $v) {
if ($k === $needleKey) {
$arr[$k] = $replacement;
} else {
if (is_array($v)) {
replaceInArray($arr[$k], $needleKey, $replacement);
}
}
}
}
replaceInArray($sourceArr, 'products', ['id' => '0004', 'filename' => 'new.jpg']);
function replaceInArrayWithKey(array &$arr, $needleKey, array $replacementArray, $replacementKey) {
foreach ($arr as $k => $v) {
if ($k === $needleKey) {
$arr[$replacementKey] = $replacementArray;
unset($arr[$k]);
} else {
if (is_array($v)) {
replaceInArrayWithKey($arr[$k], $needleKey, $replacementArray, $replacementKey);
}
}
}
}
replaceInArrayWithKey($sourceArray, 'products', ['id' => '0004', 'filename' => 'new.jpg'], 'products_new');
You can also try using a built-in recursive iterator - https://www.php.net/manual/en/class.recursivearrayiterator.php
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 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);
I have an array like below, as you can see the last array [adad] value is blank, how can I write an if statement to tell whether this is blank.
Array
(
[K] => Array
(
[0] => mabel__chan
[1] => mabel chan
)
[B] => Array
(
[0] => kieron br
)
[C] => Array
(
[0] => a br
[1] => a
)
[adad] => Array
(
[0] =>
)
)
I have tried doing this
if (count(array_filter($array)) == 0) {}
Pseudo code
if(array[key] == blank) {
echo "is blank";
} else {
echo "isn't blank";
}
**PHP Script this is how I get my data from mongoDB*
The answer below is working correctly when I use echos but now when I'm trying to push into new arrays its broken somewhere I get no data back anymore.
$col = "A" . $user->agencyID;
$db = $m->rules;
$collection = $db->$col;
$id = $_POST['ruleID'];
$search = array(
'_id' => new MongoId($id)
);
$cursor = $collection->find($search);
$validTagsArray = array();
$validArray = array();
foreach ($cursor as $key => $value) {
$temp = array_walk($array, function($v, $k) {
if (count(array_filter($v)) === 0) {
foreach ($value['AutoFix'] as $keyTwo => $valTwo) {
$x = 0;
$validTagsArray['data'][] = array($keyTwo, $x);
}
} else {
foreach ($value['AutoFix'] as $keyTwo => $valTwo) {
$x = 0;
foreach ($valTwo as $key => $value) {
$x++;
}
$validTagsArray['data'][] = array($keyTwo, $x);
}
}
});
}
echo json_encode($validTagsArray);
You can try this -
$array = array
(
'K' => array('0' => 'mabel__chan','1' => 'mabel chan'),
'B' => array('0' => 'kieron br'),
'C' => array('0' => 'a br', '1' => 'a'),
'adad' => array('0' => '')
);
$temp = array_walk($array, function($v, $k) {
if(count(array_filter($v)) === 0) { // check the count of non-empty elements in the sub array
echo $k . ' is empty';
}
});
Output
adad is empty
You can write as:
if([adad][0]== " ")
{
}
You can also try this :
foreach($array as $key=>$value){
if(empty($value))
echo "empty";
}
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);