How to get unique ids from array loop using php - php

I have the following array which I am getting as mysql result set
Array
(
[0] => Array
(
[slug] => block_three_column
[title] => CSG 2
[type_id] => 8
[entry_id] => 6
[stream_id] => 11
)
[1] => Array
(
[slug] => block_three_column
[title] => CSG
[type_id] => 8
[entry_id] => 5
[stream_id] => 11
)
)
Array
(
[0] => Array
(
[slug] => block_three_column
[title] => CSG 2
[type_id] => 8
[entry_id] => 6
[stream_id] => 11
)
[1] => Array
(
[slug] => block_three_column
[title] => CSG
[type_id] => 8
[entry_id] => 5
[stream_id] => 11
)
)
The both arrays are similar I want get the unique entry id using php.
I tried with the following code but it is producing 2 arrays again.
foreach($block_results as $rowarr)
{
foreach($rowarr as $k=>$v)
{
if($k == "entry_id")
{
$entid[] = $v;
}
}
}
Any help is highly appreciated. Thanks in advance.


You can use array_map() instead of foreach(). Example:
$entry_ids = array_unique(
array_map(
function($v){
return $v['entry_id'];
},
$array
)
);
var_dump($entry_ids);
array_unique() is to remove duplicate elements from array().

You can get the entry_id directly:
$array = array(
array(
'slug' => 'block_three_column',
'title' => 'CSG 2',
'type_id' => 8,
'entry_id' => 6,
'stream_id' => 11
),
array(
'slug' => 'block_three_column',
'title' => 'CSG',
'type_id' => 8,
'entry_id' => 5,
'stream_id' => 11
)
);
foreach ($array as $innerArray) {
if (isset($innerArray['entry_id'])) {
$entid[] = $innerArray['entry_id'];
}
}
var_dump($entid);
Output is:
array
0 => int 6
1 => int 5

Assuming that you want a list of the unique values of entry_id from the array, and it is possible that some will not have an entry_id set:
$entid = array();
foreach ( $array as $blockArray) {
if ( isset( $blockArray['entry_id'] )
&& !in_array( $blockArray['entry_id'], $entid ) ) {
$entid[] = $blockArray['entry_id'];
}
}
var_dump( $entid );

Try this:
PHP
$entid = array(); //Holds unique id's
foreach($block_results as $rowarr)
{
//Make sure entry_id exists
$entid[] = array_key_exists('entry_id',$rowarry) ? $rowarr['entry_id'] : false;
}

If they are always similiar and the same length:
foreach ($array1 as $key => $value) {
$firstValue = $array1[$key]['entry_id'];
$secondValue = $array2[$key]['entry_id'];
}
Though, keep in mind this solution is very sensitive to errors.

try this like your code:
$block_results = array(
array(
'slug' => 'block_three_column',
'title' => 'CSG 2',
'type_id' => 8,
'entry_id' => 6,
'stream_id' => 11
),
array(
'slug' => 'block_three_column',
'title' => 'CSG',
'type_id' => 8,
'entry_id' => 6,
'stream_id' => 11
),
array(
'slug' => 'block_three_column',
'title' => 'CSG',
'type_id' => 8,
'entry_id' => 7,
'stream_id' => 11
)
);
var_dump($block_results);
$entid=array();
if(count($block_results)>0)foreach($block_results as $rowarr)
{
$entid[] = $rowarr['entry_id'];
}
$entid=array_unique($entid);
var_dump($entid);
output:
array
0 =>
array
'slug' => string 'block_three_column' (length=18)
'title' => string 'CSG 2' (length=5)
'type_id' => int 8
'entry_id' => int 6
'stream_id' => int 11
1 =>
array
'slug' => string 'block_three_column' (length=18)
'title' => string 'CSG' (length=3)
'type_id' => int 8
'entry_id' => int 6
'stream_id' => int 11
2 =>
array
'slug' => string 'block_three_column' (length=18)
'title' => string 'CSG' (length=3)
'type_id' => int 8
'entry_id' => int 7
'stream_id' => int 11
array
0 => int 6
2 => int 7

Related

Getting values in array by key in multidimensional array [duplicate]

This question already has answers here:
Is there a function to extract a 'column' from an array in PHP?
(15 answers)
Closed 6 years ago.
I am trying to get values for each field eg. translation in subarrays without foreach. Is it possible?
Array
(
[0] => Array
(
[group_id] => 11
[group_translation] => Extras
[id] => 21
[operation] => +
[price] => 5
[price_by] => once
[price_type] => fixed
[translation] => Pick up
[price_total] => 5
)
[1] => Array
(
[group_id] => 11
[group_translation] => Extras
[id] => 22
[operation] => +
[price] => 10
[price_by] => once
[price_type] => fixed
[translation] => Drinks
[price_total] => 10
)
)
Thank you!
Sure that is possible:
<?php
$data = [
[
'group_id' => 11,
'group_translation' => 'Extras',
'id' => 21,
'operation' => '+',
'price' => 5,
'price_by' => 'once',
'price_type' => 'fixed',
'translation' => 'Pick up',
'price_total]' => 5
],
[
'group_id' => 11,
'group_translation' => 'Extras',
'id' => 22,
'operation' => '+',
'price' => 10,
'price_by' => 'once',
'price_type' => 'fixed',
'translation' => 'Drinks',
'price_total' => 10
]
];
$extract = [];
array_walk($data, function($element) use (&$extract) {
$extract[] = $element['translation'];
});
var_dump($extract);
The output obviously is:
array(2) {
[0] =>
string(7) "Pick up"
[1] =>
string(6) "Drinks"
}

multi-dimensional array in php

$array = array(
array(
'id' => 1,
'sht' => 'L',
'tm' => 'tttt'
),
array(
'id' => 7,
'tm' => 'xyz'
),
array(
'id' => 12,
'hand' => 'R'
),
array(
'id' => 20
)
);
$id = array_column($array, "id");
//Getting this result
Array
(
[0] => 1
[1] => 7
[2] => 12
[3] => 20
)
//Expecting like this
Array (
[id] => Array (
[H] => 1
[S] => 7
[F] => 12
[G] => 20
),
[sht] => Array (
[H] => L
[S] => ''
[F] => ''
[G] => ''
)
[tm] => Array (
[H] => tttt
[S] => xyz
[F] => ''
[G] => ''
)
[hand] => Array (
[H] => ''
[S] => ''
[F] => R
[G] => ''
)
)
I do not wish you keep indexing like 0,1,2,3 i want to put indexing like H,S,F,G how can i put it the same into my query please suggest
Also explain how key behave how can we set our defined key instead 0,1
Online Demo
check this code
$array = array(
array(
'id' => 1,
'sht' => 'L',
'tm' => 'tttt'
),
array(
'id' => 7,
'tm' => 'xyz'
),
array(
'id' => 12,
'hand' => 'R'
),
array(
'id' => 20
)
);
$newKey=array("H","S","F","G");
//Get Key list
$keyList=array();
foreach($array as $key=>$value){
foreach($value as $key2=>$value2){
if(!in_array($key2,$keyList))
$keyList[]=$key2;
}
}
//===========
$result=array();
$i=0;
foreach($array as $key=>$value){
//add '' if key does not exist
foreach($keyList as $k){
if(!array_key_exists($k,$value))
$value[$k]='';
}
//=============================
//add to new array with letter key($newkey)
foreach($value as $key2=>$value2){
$result[$key2][$newKey[$i]]=$value2;
}
//=========================================
$i++;
}

how to insert batch codeigniter

Ii everyone, I have an post data in array like this, I'm so confused how create the logic in controller:
POST Data:
Array
(
[nama_agenda] => blalala
[kilasan] => asdsadsadasd
[tgl_agenda] => 2014-06-01
[jam_agenda] => 13:27:30
[komisi] => Array
(
[0] => 1
[1] => 3
)
[fraksi] => Array
(
[0] => 1
[1] => 4
)
[badan] => Array
(
[0] => 1
[1] => 3
)
[anggota] => Array
(
[0] => 1
[1] => 4
)
[bagian] => Array
(
[0] => 2
[1] => 4
)
)
My question is how to insert into database, in controller? Thank's for help. I'll appreciate.
Since your structure is not well formed for insert_batch method. Your need to restructure it first. Consider this example:
$original_values = array(
'nama_agenda' => 'blalala',
'kilasan' => 'asdsadsadasd',
'tgl_agenda' => '2014-06-01',
'jam_agenda' => '13:27:30',
'komisi' => array(1, 3),
'fraksi' => array(1, 4),
'badan' => array(1, 3),
'anggota' => array(1, 4),
'bagian' => array(2, 4),
);
$new_values = array();
for($x = 0, $size = count($original_values['komisi']); $x < $size; $x++) {
foreach($original_values as $key => &$value) {
if(!is_array($value)) {
$new_values[$x][$key] = $value;
} else {
$new_values[$x][$key] = array_shift($value);
}
}
}
echo '<pre>';
print_r($new_values);
Should yield something like:
Array
(
[0] => Array
(
[nama_agenda] => blalala
[kilasan] => asdsadsadasd
[tgl_agenda] => 2014-06-01
[jam_agenda] => 13:27:30
[komisi] => 1
[fraksi] => 1
[badan] => 1
[anggota] => 1
[bagian] => 2
)
[1] => Array
(
[nama_agenda] => blalala
[kilasan] => asdsadsadasd
[tgl_agenda] => 2014-06-01
[jam_agenda] => 13:27:30
[komisi] => 3
[fraksi] => 4
[badan] => 3
[anggota] => 4
[bagian] => 4
)
)
Now you can use insert_batch() method.
$this->db->insert_batch('table_name', $new_values);
get all the data in array using $this->input->post() eg:
$bagian= $this->input->post('bagian');
and create a array()
$arr=array(
'db_table_col_1'=>$bagian,
'db_table_col_2'=>$post_data,
'db_table_col_2'=>$post_data
);
pass this array to model
$this->your_model_name->function_name($arr);
then in model create function
function_name($arg){
$this->db->insert('table_name',$arr);
}
if you want to insert multiple row then just use foreach
<?php
$arr1=array();
$arr= array(
'nama_agenda' => 'blalala',
'kilasan' => 'asdsadsadasd',
'tgl_agenda' => '2014-06-01',
'jam_agenda' => '13:27:30',
'komisi' => array
(
'0' => 1,
'1' => 3
),
'fraksi' => array
(
'0' => 1,
'1' => 4
),
'badan' => array
(
'0' => 1,
'1' => 3
),
'anggota' => array
(
'0' => 1,
'1' => 4
),
'bagian' => array
(
'0' => 2,
'1' => 4
)
);
foreach($arr as $row){
if(is_array($row)){
array_push($arr1,$row);
}
}
print_r($arr1);
and then pass this array to batch_insert
function_name($arr1){
$this->db->insert_batch('table_name',$arr1);
}
note arr1 syntax must be
$arr1 = array(
array(
'table_col1' => 'My title' ,
'table_col2' => 'My Name'
),
array(
'table_col1' => 'other title' ,
'table_col2' => 'other Name'
)
);
?>

Looping through array of unlimited children and display to a table

I don't have any idea how to loop through this array and display it to an HTML table. Child data are dynamic and can be unlimited. Anyone can give me a clue? Thanks!
(
[0] => Array
(
[Discount] => Array
(
[id] => 8
[parent_id] => 0
[lft] => 1
[rght] => 6
[name] => Discount 1
[value] => 25
)
[children] => Array
(
[0] => Array
(
[Discount] => Array
(
[id] => 10
[parent_id] => 8
[lft] => 2
[rght] => 5
[name] => Child of D1
[value] => 32
)
[children] => Array
(
[0] => Array
(
[Discount] => Array
(
[id] => 11
[parent_id] => 10
[lft] => 3
[rght] => 4
[name] => The 1.1.1
[value] => 65
)
[children] => Array
(
)
)
)
)
)
)
)
I know I can't just do:
foreach($discounts as $discount){
echo "<div>{$discount['Discount']['name']}</div>";
}
Try this
foreach ($Discount as $children => $value) {
echo "<div>{$discount['Discount']['$children']['name']}</div>";
}
You will need recursion to properly generate the HTML. Here is an example that I hope is helpful. This isn't exactly HOW you'll want to generate the final HTML but this should get you started on the right track:
$data = array(
0 => array(
'discount' => array(
'id' => 8,
'parent_id' => 0,
'lft' => 1,
'rght' => 6,
'name' => 'Discount 1',
'value' => 25,
),
'children' => array(
0 => array(
'discount' => array(
'id' => 10,
'parent_id' => 8,
'lft' => 2,
'rght' => 5,
'name' => 'Child of D1',
'value' => 32,
),
'children' => array(
0 => array(
'discount' => array(
'id' => 11,
'parent_id' => 10,
'lft' => 3,
'rght' => 4,
'name' => 'The 1.1.1',
'value' => 65,
),
'children' => array(),
)
)
)
)
)
);
$html = getHtml($data);
/**
* This function is called recursively to generate the necessary HTML
* #param array $data
*/
function getHtml(array $data)
{
// This is your base conditon to end the recursion. It stops once it hits an empty children array
if (empty($data)) {
return;
}
$data = $data[0]; // will have to tweak this if you have more than 1 element per array
$html = sprintf('<div id="%d" name="%s">', $data['discount']['id'], $data['discount']['name']);
$html .= getHtml($data['children']); // this recursive call generates inner HTML
$html .= '</div>';
return $html;
}
// See the result
var_dump($html);

Have the following array merged

I have the following array:
Array
(
[0] => Array
(
[Vendor_ID] => 1
[Quantity] => 55
)
[1] => Array
(
[Vendor_ID] => 1
[Quantity] => 55
)
[2] => Array
(
[Vendor_ID] => 1
[Quantity] => 55
)
[3] => Array
(
[Vendor_ID] => 3
[Quantity] =>
)
[4] => Array
(
[Vendor_ID] => 3
[Quantity] =>
)
[5] => Array
(
[Vendor_ID] => 3
[Quantity] =>
)
[6] => Array
(
[Vendor_ID] => 4
[Quantity] =>
)
[7] => Array
(
[Vendor_ID] => 4
[Quantity] =>
)
[8] => Array
(
[Vendor_ID] => 4
[Quantity] =>
)
)
Which is being created with the following code:
$Display_Arr = array();
$Tick = 0;
foreach ($_POST['product'] AS $_1){
if (!in_array($_1['vendor_id'], $Display_Arr)){
$Display_Arr[$Tick] = array(
"Vendor_ID" => $_1['vendor_id'],
"Quantity" => ""
);
$Display_Arr[$Tick]["Quantity"] .= $_1['quantity'];
}else{
$Display_Arr[$Tick]["Quantity"] .= $_1['quantity'];
}
++$Tick;
}
echo "<pre>";
print_r($Display_Arr);
echo "</pre>";
But I am not getting my desired output, which is:
Array
(
[0] => Array
(
[Vendor_ID] => 1
[Quantity] => 55,55,55
)
[1] => Array
(
[Vendor_ID] => 3
[Quantity] =>
)
[2] => Array
(
[Vendor_ID] => 4
[Quantity] =>
)
)
Where am I going wrong with this?
#mathielo
The current output is:
Array
(
[1] => Array
(
[Vendor_ID] => 1
[Quantity] => 55
)
[3] => Array
(
[Vendor_ID] => 3
[Quantity] =>
)
[4] => Array
(
[Vendor_ID] => 4
[Quantity] =>
)
)
Whereas, i'm trying to obtain:
[0] => Array
(
[Vendor_ID] => 1
[Quantity] => 55,55,55
)
If I got it right, what you need is this:
EDIT: Just made some tests and got it right this time:
$Display_Arr = array();
foreach ($_POST['product'] AS $_1){
if (!array_key_exists($_1['Vendor_ID'], $Display_Arr)){
$Display_Arr[$_1['Vendor_ID']] = array(
"Vendor_ID" => $_1['Vendor_ID'],
"Quantity" => $_1['Quantity']
);
}else{
if(!empty($_1['Quantity']))
$Display_Arr[$_1['Vendor_ID']]["Quantity"] .= ",{$_1['Quantity']}";
}
}
echo "<pre>";
print_r($Display_Arr);
echo "</pre>";
The main problem was in if (!in_array($_1['vendor_id'], $Display_Arr)). PHP's in_array() checks for given needle in the array values, and we were trying to match to the Vendor_ID value stored in the outer array keys. That was fixed using array_key_exists().
EDIT 2: I used this for test data:
$_POST['product'] = array(
0 => array(
'Vendor_ID' => 1,
'Quantity' => 55
),
1 => array(
'Vendor_ID' => 1,
'Quantity' => 55
),
2 => array(
'Vendor_ID' => 1,
'Quantity' => 55
)
,
3 => array(
'Vendor_ID' => 3,
'Quantity' => ''
),
4 => array(
'Vendor_ID' => 3,
'Quantity' => ''
),
5 => array(
'Vendor_ID' => 3,
'Quantity' => ''
),
6 => array(
'Vendor_ID' => 4,
'Quantity' => ''
),
7 => array(
'Vendor_ID' => 4,
'Quantity' => ''
),
8 => array(
'Vendor_ID' => 4,
'Quantity' => ''
)
);
You won't be needing $Tick anymore, as you could use Vendor_ID as keys for the outer array.
Looks like the easiest way to solve this would be to first aggregate the vendor quantities, and then build the final array with the keys that you are using.
I am assuming the input looks something like this:
$_POST['product'] = [
['vendor_id' => 1, 'quantity' => 55],
['vendor_id' => 1, 'quantity' => 55],
['vendor_id' => 1, 'quantity' => 55],
['vendor_id' => 3, 'quantity' => null],
['vendor_id' => 3, 'quantity' => null],
['vendor_id' => 3, 'quantity' => null],
['vendor_id' => 4, 'quantity' => null],
['vendor_id' => 4, 'quantity' => null],
['vendor_id' => 4, 'quantity' => null],
];
Aggregating the quantities:
$aggregates = [];
foreach ($_POST['product'] as $product) {
$id = $product['vendor_id'];
if ( ! isset($aggregates[$id])) {
$aggregates[$id] = [];
}
if ($product['quantity'] > 0) {
$aggregates[$id][] = $product['quantity'];
}
}
The aggregates array should now look like this:
$aggregates = [
1 => [
0 => 55,
1 => 55,
2 => 55,
],
3 => [], // Empty
4 => [], // Empty
];
As you can see the data is now neatly organized and ready to be put into any format you want. Using the keys that you use in your question it is as simple as:
$output = [];
foreach ($aggregates as $vid => $qty) {
$quantity = implode(',', $qty);
$output[] = ['Vendor_ID' => $vid, 'Quantity' => $quantity];
}
The output should now look like this:
$output = [
['Vendor_ID' => 1, 'Quantity' => '55,55,55'],
['Vendor_ID' => 3, 'Quantity' => ''],
['Vendor_ID' => 4, 'Quantity' => ''],
];
This will output exactly what you are looking for although the output of the last answer (Sverri M. Olsen) is more useful. Here you get the quantities as a string while with Sverri's method you get an array in first place.
$Display_Arr = array();
$vendors=array();
foreach ($_POST['product'] AS $_1){
if (!in_array($_1['vendor_id'],$vendors)){
$vendors[]=$_1['vendor_id'];
$Display_Arr[sizeof($vendors)-1] = array(
"Vendor_ID" => $_1['vendor_id'],
"Quantity" => $_1['quantity']
);
}
else{
$vendorKey=array_search($_1['vendor_id'],$vendors);
$Display_Arr[$vendorKey]["Quantity"] .=(!empty($Display_Arr[$vendorKey]["Quantity"])?',':null).$_1['quantity'];
}
}

Categories