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 ) )
Related
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 a multidimensional array.I want to extract this array through foreach loop and want to display in a unordered list. how to solve this. please help me. i am trying for 2 days but could not get any solution. i think i'm weak in loop.
Array
(
[id] => 1
[name] => Funny
[category_details] => Array
(
[get_everything] => Array
(
[0] => Array
(
[ci_cat_id] => 1
[img_name] => fapore kapor nosto
)
)
)
)
Array
(
[id] => 4
[name] => Events
[category_details] => Array
(
[get_everything] => Array
(
[0] => Array
(
[ci_cat_id] => 4
[img_name] => elo khushir eid
)
[1] => Array
(
[ci_cat_id] => 4
[img_name] => Eid e bari jacchi
)
)
)
)
i want the output like this
category name1:
1. test1
2. test2
3. test3
category name2:
1. test4
2. test5
3. test6
You need to use the array_column(). First of all you need to loop the array and get the category names, and also you need to get the img_name, for this you have to use the array_column and that function gives you the array of that img_name, so now again loop this new array and print the img_name.
Your array:
$arr = array(
array(
"id" => 1,
"name" => "Funny",
"category_details" => array(
"get_everything" => array(
array(
"ci_cat_id" => 1,
"img_name" => "fapore kapor nosto"
)
)
)
),
array(
"id" => 4,
"name" => "Events",
"category_details" => array(
"get_everything" => array(
array(
"ci_cat_id" => 4,
"img_name" => "elo khushir eid"
),
array(
"ci_cat_id" => 4,
"img_name" => "Eid e bari jacchi"
)
)
)
)
);
procedure:
foreach($arr as $val){
echo $val['name']."<br/>";
$i = 1;
$img_name = array_column($val['category_details']['get_everything'], 'img_name');
foreach($img_name as $v){
echo $i++.' - '.$v."<br/>";;
}
}
Output:
Funny
1 - fapore kapor nosto
Events
1 - elo khushir eid
2 - Eid e bari jacchi
Try this will may help you,
1) If you want array:
foreach ($array as $k=>$v){
foreach ($v['category_details']['get_everything'] as $key => $val){
$finalArray[$v['name']][] = $val['img_name'];
}
}
Output will look like this,
Array
(
[Funny] => Array
(
[0] => fapore kapor nosto
)
[Events] => Array
(
[0] => elo khushir eid
[1] => Eid e bari jacchi
)
)
2)If You want string :
foreach ($array as $k=>$v){
echo $v['name'].'<br/>';
$i=1;
foreach ($v['category_details']['get_everything'] as $key => $val){
echo $i.'. '.$val['img_name'].'<br/>';
$i++;
}
}
Output Will be,
Funny
1. fapore kapor nosto
Events
1. elo khushir eid
2. Eid e bari jacchi
try this one
foreach($array as $value) {
echo $value['name'];
foreach($value['category_details'] as $val) {
$i=1;
foreach($val as $v) {
echo $i++ . '. ' . $v['img_name'];
}
}
}
hope this help..
My Controller
function indexx() {
$emp['get_all_img'] = $this->model_bundle->get_all_img();
$t = $this->model_bundle->get_category();
$i = 1;
foreach ($t as $key => $data) {
//$emp['get_everything'][$key]['id'] = $data['id'];
$emp['get_everything'][$key]['name'] = $data['name'];
$emp['get_everything'][$key]['category_details'] = $this->get_category_wise_image($data['id']);
$i++;
}
$this->layout->view('bundle/add_bundle', $emp);
}
function get_category_wise_image($cat_id) {
$data = $this->model_bundle->get_category_wise_image($cat_id);
$i = 1;
foreach ($data as $key => $data) {
$emp['get_everything'][$key]['ci_cat_id'] = $data['ci_cat_id'];
$emp['get_everything'][$key]['bangla_caption'] = $data['bangla_caption'];
$emp['get_everything'][$key]['images_id'] = $data['images_id'];
$emp['get_everything'][$key]['thumnail'] = $data['thumnail'];
$i++;
}
//echo "<pre>";
//print_r($emp);
return $emp;
}
My Model
function get_all_img()
{
$this->db->select('id, bangla_caption, thumnail');
$query = $this->db->get('images');
return $query->result();
}
function get_category(){
$this->db->select('id, name');
$this->db->from('category');
$this->db->order_by('id');
$result = $this->db->get();
return $result->result_array();
}
function get_category_wise_image($id){
$this->db->select('category_images.id as id, img_id, category_images.cat_id as ci_cat_id, images.cat_id as im_cat_id, bangla_caption, name, thumnail, images.id as images_id');
$this->db->from('category_images');
$this->db->join('category','category.id = category_images.cat_id','left');
$this->db->join('images','images.id = category_images.img_id','left');
$this->db->where('category_images.cat_id',$id);
$result = $this->db->get();
return $result->result_array();
}
view(add_bundle.php)
foreach($get_everything as $tasks){
//echo "<pre>";
//print_r($tasks);
echo '<div class="cat_name">'. $tasks['name'].'</div>';
echo "<ul>";
foreach($tasks as $task){
foreach($task as $p){
foreach($p as $pr){
echo '<div height="50px">
<label><input type="checkbox" name="img_id[]" class="second" value="'.$pr['images_id'].'">';
echo '<img src="'.base_url()."uploads/".$pr['thumnail'].'" width="60px">"'.$pr['bangla_caption'].'"</label></div>';
}
}
}echo "</ul>";
}
I am confused with array.
What I want to do is two merge two array, but this kind of the two array are different:
Array
(
[0] => Array
(
[sud] => 60
[sad] => Array
(
[incharge] => Perusahaan
[perusahaan_id] => 1
[barang_id] => 3
[gudang_id] => 2
[stock] => 1
)
)
[1] => Array
(
[sud] => 23
[sad] => Array
(
[incharge] => Perusahaan
[perusahaan_id] => 1
[barang_id] => 4
[gudang_id] => 1
[stock] => 2
)
)
)
I want to move the array of [sud] into [sad] array, and named it as quantity.
This is my codes which generate the array above:
if($q->num_rows() > 0)
{
foreach ($q->result() as $row => $rows)
{
$data[] = $rows;
$stock[] = $rows->stock;
}
}
$i = -1;
foreach ($update as $updates)
{
$i++;
$test3['sud'] = $stock[$i];
$test3['sad'] = $updates;
$happy[] = $test3;
}
print_r ($happy);
What I want to do here actually is to check if the number of array [stock] => value is not bigger than the number in array [sud].
Please help, thanks in advance.
If I understood well, you want to change it like this:
if($q->num_rows() > 0)
{
foreach ($q->result() as $row => $rows)
{
$data[] = $rows;
$stock[] = $rows->stock;
}
}
$i = -1;
foreach ($update as $updates)
{
$i++;
$test3['sad'] = $updates;
$test3['sad']['quantity'] = $stock[$i];
$happy[] = $test3;
}
print_r ($happy);
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);
How can I create an array like the following in PHP from a database result set using a loop:
Array
(
[T] => Array
(
[0] => Array
(
[id] => 1
[name] => Timer
)
[1] => Array
(
[id] => 2
[name] => Tub
)
)
[P] => Array
(
[0] => Array
(
[id] => 3
[name] => Paper
)
[1] => Array
(
[id] => 4
[name] => Puppy
)
)
)
You will notice that the array keys are a letter, which is taken from the 'name' value in the result set. The loop will be something like this:
while($result = $db->fetch($query) {
$key = $result['name']{0};
// your answer :-)
}
I think something like this should do it:
$sql = 'SELECT id, name FROM table';
$result = mysql_query( $sql);
$answer = array();
while( $row = mysql_fetch_assoc( $result))
{
$answer[ strtoupper($row['name'][0]) ][] = $row;
}
mysql_free_result( $result);
var_dump( $answer);
OR, to be more specific (if your query is returning more columns than just id and name):
while( $row = mysql_fetch_assoc( $result))
{
$answer[ strtoupper($row['name'][0]) ][] = array(
'id' => $row['id'],
'name' => $row['name']
);
}
$indexArray = array(); // Array from Example
while($result = $db->fetch($query) {
$key = $result['name']{0};
if(!isset($indexArray[$key])) {
$indexArray[$key] = array();
}
array_push($indexArray[$key], $result);
}
$results = array();
while($result = $db->fetch($query)) {
$key = strtoupper($result['name'][0]);
if(!isset($results[$key]))
$results[$key] = array();
$results[$key][] = $result;
}