So far my var_dump() of a $records array looks like:
array (size=1)
25 =>
array (size=1)
0 =>
object(stdClass)[51]
public 'id' => 25
public 'name' => info...
public 'surname' => info...
I wan't to change that 0 index name to object id (25) name but it just adds one more dimension above my current one. This is how I do it:
foreach ($records as $value) {
$records = array($value->id=>$records);
}
I want my array to look like this though:
array (size=1)
25 =>
object(stdClass)[51]
public 'id' => 25
public 'name' => info...
public 'surname' => info...
Updating keys so they equal the ID:
$tmp= array();
foreach ($records as $value) {
$tmp[$value->id] = $value;
}
$records = $tmp;
Related
I am trying to create and array to fill for my form_dropdown() for my view:
<?php echo form_dropdown('vendor', $vendors, '', 'class="form-control"') ?>
However, I am only getting the last value based on the function that generates the array:
public function get_vendors() {
$vendors = $this->db->table('vendor')->get()->getResultArray();
// Return key => value pair array
$array = array(
0 => 'Not Assigned'
);
if (!empty($vendors)) {
foreach ($vendors as $vendor) {
$array = array(
$vendor['id'] => $vendor['vendor']
);
}
}
return $array;
}
This function is within my model. The only problem I have is that it's returning only the last row from the table. However when I do a var_dump() for the $vendors I get all the rows. Not sure what I am doing wrong.
array (size=2)
0 =>
array (size=4)
'id' => string '1' (length=1)
'vendor' => string 'Blue Chip' (length=9)
'datecreated' => string '2022-08-16' (length=10)
'datemodified' => string '2022-08-16' (length=10)
1 =>
array (size=4)
'id' => string '2' (length=1)
'vendor' => string 'ASP' (length=3)
'datecreated' => string '2022-08-30' (length=10)
'datemodified' => string '2022-08-31' (length=10)
Changing the query to from getResultArray() to getResultObject() did the trick. So I was able to use $array[$vendor->id] = $vendor->vendor;
public function get_vendors() {
$vendors = $this->db->table('vendor')->get()->getResultObject();
// Return key => value pair array
$array = array(
0 => 'Not Assigned'
);
if (!empty($vendors)) {
foreach ($vendors as $vendor) {
$array[$vendor->id] = $vendor->vendor;
}
}
return $array;
}
If you still want to use getResultArray():
public function get_vendors() {
$vendors = $this->db->table('vendor')->get()->getResultArray();
// Return key => value pair array
$array = array(
0 => 'Not Assigned'
);
if (!empty($vendors)) {
foreach ($vendors as $vendor) {
$array[$vendor['id']] => $vendor['vendor'];
}
}
return $array;
}
My problem is i have a multidimensional array posting from form to php, now i want to checking if duplicate values of some indexes exist in multi dimensional array or not?
e.g:
$data=Array
(
0 => Array
(
uid => '100',
name => 'Sandra Shush',
type => 'abc'
),
1 => Array
(
uid => '101',
name => 'Sandra Shushtext',
type => 'xyz'
),
2 => Array
(
uid => '100',
name => 'Sandra Shush',
type => 'abc'
)
);
here name and type of index 1 and 2 are same, so how can i check it?
I am familiar with
$key = array_search('abc', array_column($data, 'type'));
but it is for duplication of single column value in multi rows, in my situation if multi column of same rows same with multi column of any other row then record will be consider as duplicate.
Any help should be appreciated, Thanks in advance.
You can try using array_reduce by creating a key using your desired item keys:
$result = array_reduce($data, function ($carry, $item) {
$key = $item['uid'] . $item['type'];
$item['is_duplicate'] = isset($carry[$key]);
if ($item['is_duplicate']) {
$carry[] = $item;
} else {
$carry[$key] = $item;
}
return $carry;
}, []);
var_dump($result);
The easiest way, well at least the one I would use is to encode your arrays into md5 (or any other kind) string and compare those values. I think it is the most efficient in your case.
Example:
<?php
function arrayToString($array) {
$str = '';
if ( !is_array($array) )
return $str;
foreach ( $array as $key => $val ) {
$str .= $key . ':' . $val;
}
return $str;
}
$data=Array
(
0 => Array
(
'uid' => '100',
'name' => 'Sandra Shush',
'type' => 'abc'
),
1 => Array
(
'uid' => '100',
'name' => 'Sandra Shush',
'type' => 'xyz'
),
2 => Array
(
'uid' => '100',
'name' => 'Sandra Shush',
'type' => 'abc'
)
);
$temp = array();
foreach ( $data as $d ) {
array_push($temp, md5(arrayToString($d)));
}
$unique = array_unique($temp);
var_dump($unique); // prints unique array
This is a very fast designed approach and will find duplicates. Note that duplicates are elements which have the same value for the same key. So if any of uid, name or type match, they will be treated as duplicates. Therefore I adjust the third array element, because all elements in your array share the same values.
$data = [
....
2 =>
[
'uid' => '200',
'name' => 'Mandra Shush',
'type' => 'abcx'
]
];
$duplicates = [];
$valuesToCompare = ["uid", "name", "type"];
function equals($value, $toCompare, $keysToCompare)
{
foreach ($keysToCompare as $compareKey) {
if ($value[$compareKey] === $toCompare[$compareKey]) {
return true;
}
}
return false;
}
foreach ($data as $index => $element) {
foreach ($data as $indexInner => $elementToCompare) {
if ($index !== $indexInner) {
if (equals($element, $elementToCompare, $valuesToCompare)) {
$duplicates[] = [$index => $indexInner];
}
}
}
}
var_dump($duplicates);
This will output the following, which indicates we found 2 duplicates. Where element 0 is duplicate of 1, and 1 is duplicate of 0.
array (size=2)
0 =>
array (size=1)
0 => int 1
1 =>
array (size=1)
1 => int 0
I achieved above scenario like this:
Dont know which one is best mine or other's who posted answers.
foreach($data as $key => $row)
{
$combinedarr[] = array("name"=>$row["name"],"type"=>$row["type"]);
}
//chck if same facilitiy is being visit on same date twice
$countcomb = count($combinedarr);
$uniquearr = array_unique($combinedarr, SORT_REGULAR);
if($countcomb==count($uniquearr)){
}else{
//yes duplicate exists
};
Thanks again for those who answered.
I have an array that give objects back like this:
array (size=61)
0 =>
object(Xxx\Car)[602]
private 'id' => int 53
private 'name' => string 'Volkswagen' (length=10)
1 =>
object(Xxx\Car)[594]
private 'id' => int 43
private 'name' => string 'Toyota' (length=6)
2 =>
object(Xxx\Car)[595]
private 'id' => int 32
private 'name' => string 'BMW' (length=3)
How can I convert the array to so that the id become the key and the value the description, like this:
array (size=61)
53 => 'Volkswagen'
43 => 'Toyota'
32 => 'BMW'
I've tried
$cars = array();
foreach ($result as $key => $value) {
$cars[$value['id']] = $value['name'];
}
But that doesn't work.
You are treating your objects as if they were arrays.
$array['key'] is the notation for accessing an element in an array, but $object->key is the one for an object.
Try this :
$cars = array();
foreach ($result as $key => $value) {
$cars[$value->id] = $value->name;
}
EDIT : If that doesn't work (due to the private nature of the elements), you might have to declare functions like getID() and getName() in your object class file, and use them as such :
$cars = array();
foreach ($result as $key => $value) {
$cars[$value->getID()] = $value->getName();
}
Use the $arr = get_object_vars($obj); function. It converts an object to an array.
I am trying to remove pieces of a multidimensional array if a certain condition is met. The array can be as shown below, call it $friends:
array (size=3)
0 =>
array (size=1)
0 =>
object(stdClass)[500]
public 'id' => int 2
public 'first_name' => string 'Mary' (length=4)
public 'last_name' => string 'Sweet' (length=5)
1 =>
array (size=1)
0 =>
object(stdClass)[501]
public 'id' => int 9
public 'first_name' => string 'Joe' (length=3)
public 'last_name' => string 'Bob' (length=3)
2 =>
array (size=1)
0 =>
object(stdClass)[502]
public 'id' => int 1
public 'first_name' => string 'Shag' (length=4)
public 'last_name' => string 'Well' (length=4)
I have a function called is_followed, that let's me see if the id of one of the people in the array is being followed by the "user". The code I am trying is:
//remove followed friends from the $friends array
$i=0;
foreach($friends as $friend) {
foreach($friend as $f) {
if(Fanfollow::is_followed($id,$f->id)) {
unset($friend[$i]);
}
}
$i++;
}
The $id is the id of the current user.
However, this is not working. I know that using unset on $friend and not $friends is probably the issue. But using unset on $friends also won't work, because it is the higher level array. Any ideas? Thank you.
If you're trying to take down the first parent keys, use the first foreach keys instead:
foreach($friends as $i => $friend) {
// ^ assign a key
foreach($friend as $f) {
if(Fanfollow::is_followed($id,$f->id)) {
unset($friends[$i]);
// unset this
}
}
}
Or if only for that single friend:
foreach($friends as $friend) {
foreach($friend as $i => $f) {
// ^ this key
if(Fanfollow::is_followed($id,$f->id)) {
unset($friend[$i]);
// unset this
}
}
}
array_filter comes to the rescue:
array_filter($friend,
function($f) use($id) { return Fanfollow::is_followed($id,$f->id)); }
);
Though the solution with foreach is legit, array_filteris much more clear and sematically correct.
I have an 2d array that contains a 'title' and 'url' (both strings) as shown below. Is it possible to check for duplicates in the 'url' and if they exist, delete the corresponding 'title' too?
array
0 =>
array
'title' => string 'China - Wikipedia, the free encyclopedia'
'url' => string 'http://en.wikipedia.org/wiki/China'
1 =>
array
'title' => string 'China'
'url' => string 'http://www.state.gov/r/pa/ei/bgn/18902.htm'
2 =>
array
'title' => string 'China | World news | The Guardian'
'url' => string 'http://www.guardian.co.uk/world/china'
3 =>
array
'title' => string 'China Travel Information and Travel Guide - Lonely Planet'
'url' => string 'http://www.lonelyplanet.com/china'
4 =>
array
'title' => string 'ChinaToday.com'
'url' => string 'http://www.chinatoday.com/'
Try this function it could do the job
function super_unique($array,$key)
{
$temp_array = array();
foreach ($array as &$v) {
if (!isset($temp_array[$v[$key]]))
$temp_array[$v[$key]] =& $v;
}
$array = array_values($temp_array);
return $array;
}
$yourearray = super_unique($arr,'url');
Or if you are happy with using the last value of the url you could
foreach($array as $subarray) {
$output[$subarray['url']] = $subarray['title'];
}
Try something like this:
$originals = array();
foreach($array as $key => $value) {
if(!isset($originals[$value['url']])) {
$originals[$value['url']] = true;
}
else {
// exists already, delete entry
unset($array[$key]);
}
}