I have a multidimensional array of the following structure and I want to remove duplicates from it. For example if the ["amount"] is the same for two ["cities"] but the ["time"] is the same or different then I count this is a duplicate and want to remove this node from the array.
In the following example I want to remove completely node 0 from the array as the city and amount are the same as node 1. They are both Bristol (Bristol, United Kingdom) and 373 Even though the time is different being 17:15 and 17:16.
If the times are different as in this case then I would remove the later time.
array(8) {
[0]=>
array(3) {
["time"]=>
string(5) "17:16"
["city"]=>
string(33) "Bristol (Bristol, United Kingdom)"
["amount"]=>
int(373)
}
[1]=>
array(3) {
["time"]=>
string(5) "17:15"
["city"]=>
string(33) "Bristol (Bristol, United Kingdom)"
["amount"]=>
int(373)
}
[2]=>
array(3) {
["time"]=>
string(5) "17:16"
["city"]=>
string(37) "Wednesbury (Sandwell, United Kingdom)"
["amount"]=>
int(699)
}
[3]=>
array(3) {
["time"]=>
string(5) "17:16"
["city"]=>
string(45) "Wolverhampton (Wolverhampton, United Kingdom)"
["amount"]=>
int(412)
}
[4]=>
array(3) {
["time"]=>
string(5) "17:15"
["city"]=>
string(33) "Swansea (Swansea, United Kingdom)"
["amount"]=>
int(249)
}
[5]=>
array(3) {
["time"]=>
string(5) "17:16"
["city"]=>
string(39) "Watford (Hertfordshire, United Kingdom)"
["amount"]=>
int(229)
}
[6]=>
array(3) {
["time"]=>
string(5) "17:14"
["city"]=>
string(39) "Nottingham (Nottingham, United Kingdom)"
["amount"]=>
int(139)
}
[7]=>
array(3) {
["time"]=>
string(5) "17:13"
["city"]=>
string(31) "Dartford (Kent, United Kingdom)"
["amount"]=>
int(103)
}
}
Try this:
$result = array();
foreach ($array as $place) {
if (!array_key_exists($place['time'], $result)) {
$result[$place['time']] = $place;
}
}
<?php
$data = array(
array(
'time' => '17:16',
'city' => 'Bristol',
'amount' => 373,
),
array(
'time' => '18:16',
'city' => 'Bristol',
'amount' => 373,
),
array(
'time' => '18:16',
'city' => 'Wednesbury',
'amount' => 699,
),
array(
'time' => '19:16',
'city' => 'Wednesbury',
'amount' => 699,
),
);
$tmp = array();
foreach ($data as $row) {
$city = $row['city'];
$amount = $row['amount'];
if (!isset($tmp[$city][$amount])
|| $tmp[$city][$amount]['time'] < $row['time']) {
$tmp[$city][$amount] = $row;
}
}
$data = array();
foreach ($tmp as $cities) {
foreach ($cities as $city) {
$data[] = $city;
}
}
var_dump($data);
Create a 2-dimensional associative array, where one dimension is keyed off the city, and the other is the amount:
$assoc = array();
foreach ($data as $el) {
$city = $el['city'];
$amount = $el['amount'];
if (isset($assoc[$city]) {
$assoc[$city][$amount] = $el;
} else {
$assoc[$city] = array($amount => $el);
}
}
// Now gather up all the elements back into a single array
$result = array();
foreach ($assoc as $cities)
foreach ($cities as $city) {
$result[] = $city;
}
}
Related
I have an array which I want to iterate over to push the items into a select box, but I can't figure out how to do it.
The array I get from the function:
array(2) {
["de"]=> array(10) {
["id"]=> int(10)
["order"]=> int(1)
["slug"]=> string(2) "de"
["locale"]=> string(5) "de-DE"
["name"]=> string(7) "Deutsch"
["url"]=> string(34) "http://localhost/werk/Mol/de/haus/"
["flag"]=> string(66) "http://localhost/werk/Mol/wp-content/plugins/polylang/flags/de.png"
["current_lang"]=> bool(false)
["no_translation"]=> bool(false)
["classes"]=> array(4) {
[0]=> string(9) "lang-item"
[1]=> string(12) "lang-item-10"
[2]=> string(12) "lang-item-de"
[3]=> string(15) "lang-item-first"
}
}
["nl"]=> array(10) {
["id"]=> int(3)
["order"]=> int(2)
["slug"]=> string(2) "nl"
["locale"]=> string(5) "nl-NL"
["name"]=> string(10) "Nederlands"
["url"]=> string(26) "http://localhost/werk/Mol/"
["flag"]=> string(66) "http://localhost/werk/Mol/wp-content/plugins/polylang/flags/nl.png"
["current_lang"]=> bool(true)
["no_translation"]=> bool(false)
["classes"]=> array(4) {
[0]=> string(9) "lang-item"
[1]=> string(11) "lang-item-3"
[2]=> string(12) "lang-item-nl"
[3]=> string(12) "current-lang"
}
}
}
I tried a foreach but I did only get the indexes of the array
<?php
$translations = pll_the_languages(array('raw' => 1));
$lang_codes = array();
foreach ($translations as $key => $value) {
array_push($lang_codes, $key);
}
?>
I need the language slug, URL, and flag from all indexes in this array (de & nl), what should I do?
A simple iteration over the outer array and then pick the values you want from the sub array.
<?php
$translations = pll_the_languages(array('raw' => 1));
$lang_codes = array();
foreach ($translations as $lang => $info) {
$lang_codes[$lang] = [ 'slug' => $info['slug'],
'url' => $info['url'],
'flag' => $info['flag']
];
}
?>
You can approach this as
$res = [];
foreach($translations as $key => $value){
$res[$key] = [
'slug' => $value['slug'],
'url' => $value['url'],
'flag' => $value['flag']
];
}
Live Demo
Data is coming from 2 differents SQL request, so i have 2 arrays like :
FIRST ARRAY
array(6) {
[0]=>
array(2) {
["edible"]=>
string(3) "600"
["Food"]=>
string(4) "Fruit"
}
[1]=>
array(2) {
["edible"]=>
string(3) "500"
["Food"]=>
string(6) "Vegetables"
}
[2]=>
array(2) {
["edible"]=>
string(4) "1000"
["Food"]=>
string(3) "meat"
}
...
SECOND ARRAY
array(5) {
[0]=>
array(2) {
["out-of-date"]=>
string(3) "17"
["Food"]=>
string(4) "Fruit"
}
[1]=>
array(2) {
["out-of-date"]=>
string(3) "54"
["Food"]=>
string(3) "Vegetables"
}
[2]=>
array(2) {
["out-of-date"]=>
string(2) "60"
["Food"]=>
string(3) "meat"
}
...
What i would like is to merge the two arrays, but not with a function like array_merge or array_merge_recursive.
Because i would like to just add a row (key + value) like
["out-of-date"]=>
string(3) "17""
in the first array if we have the same Food (key)
output result desired :
array(6) {
[0]=>
array(3) {
["out-of-date"]=>
string(3) "17"
["edible"]=>
string(3) "600"
["Food"]=>
string(4) "Fruit"
}
...
You need to make a loop inside loop and verify the food key, if is equal merge the values to another array, Try this code:
<?php
$array1 = array();
$array1[] = array('food' => 'Fruit', 'edible' => '600');
$array1[] = array('food' => 'Vegetables', 'edible' => '500');
$array1[] = array('food' => 'meat', 'edible' => '700');
$array2 = array();
$array2[] = array('food' => 'Fruit', 'out-of-date' => '17');
$array2[] = array('food' => 'Vegetables', 'out-of-date' => '15');
$array_merged = array();
foreach ($array1 as $key => $value) {
$array_merged[$key] = $value;
foreach ($array2 as $ke => $val) {
if ($val['food'] == $value['food']) {
$array_merged[$key]['out-of-date'] = $val['out-of-date'];
}
}
}
print_r($array_merged);
I'm not sure about structure of your database table. But let's you have two tables in your MySql database:
First - edible | Food
Second - out_of_date | Food
So you can query your array by using join mysql operation. You need sql like below:
SELECT *
FROM First
LEFT JOIN Second ON First.Food=Second.Food
Also, you can use additional conditions for all tables like:
SELECT *
FROM First
LEFT JOIN Second ON First.Food=Second.Food
WHERE First.edible = 1000 AND Second.out_of_date = 10
You can find more information here: http://dev.mysql.com/doc/refman/5.7/en/join.html
The question might be silly. But I am stucked in here. :( I am getting all of my database value as an object in controller.
This is how I am fetching database value:
$points = $this->CI->modelgraph->get($user_id);
It is getting all of the data corresponding to that user. This is my sample database table from where I am fetching data:
id user_id b_value h_value date r_value
1 24 330 6.2 10.11.2014 90
2 25 334 6.2 10.11.2014 92
This is static data, phpgraphlib provide in the tutorial.
$data = array("1" => .0032, "2" => .0028, "3" => .0021, "4" => .0033,
"5" => .0034, "6" => .0031, "7" => .0036, "8" => .0027, "9" => .0024,
"10" => .0021, "11" => .0026, "12" => .0024, "13" => .0036,
"14" => .0028, "15" => .0025);
I need to extract the fetched data in this manner:
$data = array("h_value" => b_value,);
How could achieve this? What will be the logic? Any help would be really appreciable.
Here is my approach.. but also not complete.. What I am doing wrong?
$total=count($points);
$i=1;
$dataArray=array();
while($i <= $total) {
foreach($points as $value) {
//echo $value -> h_value;
$field = $value -> h_value;
$labels = $value -> b_value;
$dataArray[$i][$field ] = $labels;
$i++;
}
}
When I var_dump($dataArray); Its giving me this output:
array(11) { [1]=> array(1) { ["6.6"]=> string(3) "358" } [2]=> array(1) { ["7.4"]=> string(3) "201" } [3]=> array(1) { ["6.5"]=> string(3) "144" } [4]=> array(1) { ["6.5"]=> string(3) "112" } [5]=> array(1) { ["6.2"]=> string(3) "144" } [6]=> array(1) { ["6.2"]=> string(3) "185" } [7]=> array(1) { ["7.0"]=> string(3) "176" } [8]=> array(1) { ["7.5"]=> string(3) "234" } [9]=> array(1) { ["6.5"]=> string(3) "365" } [10]=> array(1) { ["6.2"]=> string(3) "110" } [11]=> array(1) { ["4.2"]=> string(3) "100" } }
But When I var_dump($data); Its giving this:
array(15) { [1]=> float(0.0032) [2]=> float(0.0028) [3]=> float(0.0021) [4]=> float(0.0033) [5]=> float(0.0034) [6]=> float(0.0031) [7]=> float(0.0036) [8]=> float(0.0027) [9]=> float(0.0024) [10]=> float(0.0021) [11]=> float(0.0026) [12]=> float(0.0024) [13]=> float(0.0036) [14]=> float(0.0028) [15]=> float(0.0025) }
Its clearly visible I have messed up . Where is the wrong ?
Here is the output I print_r($points); Its giving this:
Array ( [0] => stdClass Object ( [id] => 12 [user_id] => 24 [b_value] => 358 [h_value] => 6.6 [rec_date] => 2014-09-19 [rec_time] => [h_value] => 1[date_added] => 2012-09-19 16:38:05 [date_modified] => 0000-00-00 00:00:00 ) [1] ..........
Please see below code.
It is self-explanatory.
Replace your values accordingly.
<?php
function modelFunction($user_id) {
$this->db->select('h_value, b_value');
$this->db->from('YOUR_TABLE_NAME');
$this->db->where('user_id', $user_id);
$query = $this->db->get();
$arr = array();
if ($query->num_rows()) {
$i=0;
foreach ($query->result_array() as $row) {
extract($row);
$arr[$i][$h_value] = $b_value;
++$i;
}
}
}
?>
Controller:
<?php
$points = $this->CI->modelFunction->get($user_id);
?>
Answer edited as per OP's request:
<?php
$dataArray = array();
for ($i=0 ; $i<= $total ; $i++) {
$value = $points[$i];
$field = $value->h_value;
$labels = $value->b_value;
$dataArray[$i][$field ] = $labels;
$i++;
}
?>
$new_array = array();
foreach($points as $point){
$new_array[] = array(
'id' => $point->id,
'user_id' => $point->user_id
);
}
Nice little helper function:
function object_to_array($data)
{
if (is_object($data)) {
$data = get_object_vars($data);
}
if (is_array($data)) {
return array_map(__FUNCTION__, $data);
}
else {
return $data;
}
}
example usage:
$data['points'] = $this->CI->modelgraph->get($user_id);
$data['points'] = object_to_array($data['points']);
I have an array like:
print_r($arr);
array(2) {
["'type'"]=>
array(3) {
[0]=>
string(17) "tell" // <----
[1]=>
string(6) "mobile" // <----
[2]=>
string(6) "address" // <----
}
["'value'"]=>
array(3) {
[0]=>
string(11) "+00.0000000" // tell
[1]=>
string(11) "12345678" // mobile
[2]=>
string(11) "Blah SQ." // address
}
}
I want a final string like:
tell = +00.0000000<br />mobile = 12345678<br />address = Blah SQ.
Now it's been more than an hour I'm struggling with this but no results yet, anyone could help me with this? I would appreciate anykind of help.
Thanks
=======================================
What I have tried:
$arr is an array so I did:
foreach($arr as $values){
// here also $values is an array, so I needed another foreach to access to items:
$i = 0;
foreach($values as $items){
// now making the final output
#$output.= $items['type'][$i] . '=' . $items['value'][$i] . '<br />';
$i++;
}
}
I'd go for array_combine(). Basically it does what you request:
$yourArray = [
"type" => ["tell", "mobile", "address"],
"value" => ["+00.0000000", "12345678", "Blah SQ."]
];
$combined = array_combine($yourArray["type"], $yourArray["value"]);
will be
$combined = [
"tell" =>"+00.0000000",
"mobile" =>"12345678",
"address" =>"Blah SQ."
];
Lastly, you can iterate through that array and then join the values:
$finalArray=array();
foreach($combined as $type=>$value)
$finalArray[]="$type=$value";
$string = join("<br/>", $finalArray); // Will output tell=+00.000000<br/>mobile=12345678<br/>address=Blah SQ.
It's not the fastest method but you'll learn quite a bit about arrays.
EDIT (using array_combine by #Dencker)
foreach($arr as $values) {
// here also $values is an array, so I needed another foreach to access to items:
$v = array_combine($values["'type'"], $values["'value'"]);
foreach($v as $key => $val) {
// now making the final output
$output.= $key . '=' . $val . '<br />';
}
}
Try this
$arr = array(
array(
"'type'" => array('tell', 'mobile', 'address'),
"'value'" => array('+00000', '123123', 'foo')
),
array(
"'type'" => array('tell', 'mobile', 'address'),
"'value'" => array('+10000', '123123', 'bar')
),
array(
"'type'" => array('tell', 'mobile', 'address'),
"'value'" => array('+20000', '123123', 'foobar')
),
);
var_dump($arr);
$output = '';
foreach($arr as $values) {
// here also $values is an array, so I needed another foreach to access to items:
$i = 0;
foreach($values as $items) {
// now making the final output
$output.= $values["'type'"][$i] . '=' . $values["'value'"][$i] . '<br />';
$i++;
}
}
echo $output;
You were referencing the other array in the second loop.
=============================================================
EDIT:
var_dump($arr);
array(3) {
[0]=> array(2) {
["type"]=> array(3) {
[0]=> string(4) "tell"
[1]=> string(6) "mobile"
[2]=> string(7) "address"
}
["value"]=> array(3) {
[0]=> string(6) "+00000"
[1]=> string(6) "123123"
[2]=> string(3) "foo"
}
}
[1]=> array(2) {
["type"]=> array(3) {
[0]=> string(4) "tell"
[1]=> string(6) "mobile"
[2]=> string(7) "address"
}
["value"]=> array(3) {
[0]=> string(6) "+10000"
[1]=> string(6) "123123"
[2]=> string(3) "bar"
}
}
[2]=> array(2) {
["type"]=> array(3) {
[0]=> string(4) "tell"
[1]=> string(6) "mobile"
[2]=> string(7) "address"
}
["value"]=> array(3) {
[0]=> string(6) "+20000"
[1]=> string(6) "123123"
[2]=> string(6) "foobar"
}
}
}
OUTPUT:
tell=+00000
mobile=123123
tell=+10000
mobile=123123
tell=+20000
mobile=123123
I have the array below:
[1]=>
array(2) {
[0]=>
object(stdClass)#23 (7) {
["AddressesTableID"]=> string(1) "8"
["AccreditNo"]=> string(13) "5129876de28ff"
["Type"]=> string(4) "home"
["Street"]=> string(34) "Wallace, Village, Under the bridge"
["Municipality"]=> string(8) "Tortuous"
["Province"]=> string(8) "Sardonic"
["ContactNo"]=> string(8) "92012010"
}
[1]=>
object(stdClass)#24 (7) {
["AddressesTableID"]=> string(1) "9"
["AccreditNo"]=> string(13) "5129876de28ff"
["Type"]=> string(6) "office"
["Street"]=> string(25) "Rasputin Query, Palpitate"
["Municipality"]=> string(7) "Opulent"
["Province"]=> string(6) "Number"
["ContactNo"]=> string(8) "29101011"
}
}
Can you guys help me on how to transform this into:
Where all the values are grouped as an array into similar keys?
["AccreditNo"]=> array(2) { "5129876de28ff", "GKIJUGUIKGI" }
["Type"]=> array(2) { "home", "home" }
["Street"]=> ...
["Municipality"]=> ...
["Province"]=> ...
["ContactNo"]=> ...
Try with:
$input = array( /* your input data*/ );
$output = array();
foreach ( $input as $data ) {
foreach ( $data as $key => $value ) {
if ( !isset($output[$key]) ) {
$output[$key] = array();
}
$output[$key][] = $value;
}
}
You can use the array_merge_recursive() function, as follows:
$arr = array_merge_recursive($arr1, $arr2)
for more information, please see here:http://www.php.net/manual/en/function.array-merge-recursive.php