CodeIgniter indexed array on query - php

How can I receive indexed array after mysql query? Or is there any method to convert $this->db->get() into mysql resource? Or convert associative array to indexed?

PHP has a function array_values() that will return an array of just the values.
http://it.php.net/manual/en/function.array-values.php

Example on converting codeigniter result_array to indexed Array:
$query = $this->db->query("SELECT `tag_id` FROM `tags`");
$arr = $query>result_array();
print_r($arr); //codeigniter default result array
//Output:
Array
(
[0] => Array
(
[tag_id] => 1
)
[1] => Array
(
[tag_id] => 3
)
)
Now If You want to convert above array to indexed Array then you have to use array_column() function which convert it associative array to indexed array by taking array key as argument see Below for example:
$query = $this->db->query("SELECT `tag_id` FROM `tags`");
$tags = $query>result_array();
$arr = array_column($tags, "tag_id");
print_r($arr); //converted indexed array
//Output:
Array
(
[0] => 1
[1] => 3
)

It looks like you might be using PHP CodeIgniter. CodeIgniter's DB implementation doesn't support indexed result arrays, you have to choose between object or associative array.
This is done to make your queries more maintainable, as returning numeric indexes are harder to debug and maintain.
Code Igniter User Guide - database results

Related

Compare Dates from Array with multidimensional array [duplicate]

I have a multidimensional array like this:
Array (
[0] => Array
(
[time] => 1364685993
[memberid] => 131
)
[1] => Array
(
[time] => 1364685994
[memberid] => 133
)
[2] => Array
(
[time] => 1364685995
[memberid] => 141
)
)
and a single-dimensional array like this:
Array (
[0] => 131
[1] => 141
[2] => 191
[3] => 205
)
Now I want to remove all Sub-arrays from multidimensional arrays that DOES NOT contain the memberid value from normal array ?
In this case only Subaray[1] to be removed from multidimensional array as it's 'memberid' key value (133) doesn't show in normal array. Those arrays are actually pretty big, so I am not sure what would be fastest way to do it ?
$normalArray = array_flip($normalArray);
$multiDimArray = array_filter($multiDimArray, function ($elem) use ($normalArray) {
return isset($normalArray[$elem['memberid']]);
});
Requires exactly two iterations, one over each array. Key lookups using $normalArray[$elem['memberId']] are blazingly fast. May have some memory overhead due to the functional nature and copies of arrays, use a traditional loop and unset if that's an issue.
First, I would flip the $nomal array to get constant lookup time into the array, like this:
$normal = array_flip( $normal);
Then, you just have to filter the $multidimensional_array by the $normal array with a simple lookup:
$filtered = array_filter( $multidimensional_array, function( $el) use( $normal) {
return isset( $normal[ $el['member_id'] ]);
});
Don't have access to development resources at the moment to test but this should work.
foreach($members as $member => $property) {
if (!in_array($property['member_id'], $id_array)) {
unset($members[$member]);
}
}
$id_array is the 1-dimensional matrix (array) you've put in your question.
Instead of filtering the database results after the fact you may want to use the single-dimensional array in the database query itself.
We do not know what the query, you are using, looks like, but something along these lines would do it:
// The ids from the file
$use_ids = array(131, 141, 191, 205);
// Create a list for the IN clause
$ids = '(' . implode(',', $use_ids) . ')';
// Create the query
$query = <<< SQL
SELECT time, memberid
FROM some_table
WHERE ...
AND memberid IN {$ids}
ORDER BY time
SQL;
// Execute the query, etc.
It is always a good idea to let the SQL handle as much filtering of content as possible.

How do I reorganize an array in PHP?

I am trying to figure out how to reorganize an array..
I have a multidimensional array(Ill call that original_array) and I would like to take the first array within original_array and set the values as keys in a new array. I also want to take the values of the second array in original_array and make them keys and then set the values of the third array in original_array as the values for those keys.
Here is an example of original_array:
Array (
[id] => Array (
[0] => 1
[1] => 3
)
[reward] => Array (
[0] => Movie
[1] => Trip
)
[cost] => Array (
[0] => 50
[1] => 200
)
)
Basically what I would like to do is look like this:
Array (
[1] => Array (
[Movie] => 50
)
[3] => Array (
[Trip] => 200
)
)
Is there a simple and elegant way to merge these like this?
I have spent hours trying to figure this out using array_merge, array_merge_recursive.. etc. And have search SO far and wide for a similar questions, but I haven't found anything that does what I am after.
I was able to correctly combine the 2nd and 3rd arrays in original_array with array_combine. But, I am at a loss as how to combine that result with the 1st array's values in original_array.
Thanks in advance to any help!
Well, the dirty way would be just use combine array functions like array_combine with the input:
$new_array = array_combine(
$array['id'], // parent keys
// combine chunked combined sub keys :p
array_chunk(array_combine($array['reward'], $array['cost']), 1, true)
);
There may be some incantation of array_*() merging functions that could produce what you're looking for, but it is far easier to just iterate over the original array's [id] sub-array and use its values to create new sub-array keys in a different output array.
// To hold your output
$output = array();
// Iterate the original array's [id] sub-array
foreach ($original['id'] as $idxkey => $newkey) {
// Add a sub-array using $newkey to the output array
$output[$newkey] = array(
// Using the index (not value), retrieve the corresponding reward
// value to use as the new array key
// and corresponding cost to use as the new subarray value
$original['reward'][$idxkey] => $original['cost'][$idxkey]
);
}
Here is a demonstration: https://3v4l.org/2pac3
This should work for you:
First you can get the keys for the main array into a separate variable with array_shift(), which will just remove the first element from your array, which is the array holding the keys.
Then use array_map() to loop through both of your subArrays and use reward as key with the cost values as value and return it in an array. At the end you just have to array_combine() your keys $keys with the new created array.
Code:
<?php
$keys = array_shift($arr);
$result = array_combine($keys, array_map(function($k, $v){
return [$k => $v];
}, $arr["reward"], $arr["cost"]));
print_r($result);
?>
You might wanna take a look at BaseArrayHelper from Yii 2.0 Framework.
Although this file is part of a framework it has only very few dependencies and you should be able to use just this file or parts of it in your code with small modifications.
An example for your use case can be found in the index() method.

Displaying result of first array in array_diff

I am using codeigniter.
I want difference of two array as I am using array_diff function of php.
Due to associative array, I have used call_user_func_array and I got record.
$result_sun = call_user_func_array('array_merge', $data['sun_holiday']);
$result_sat = call_user_func_array('array_merge', $data['third_sat']);
But when I am going to make difference of these two array like,
$result = array_diff($result_sun,$result_sat);
It only shows the record of first array $result_sun.
$result_sun = Array
(
[0] => 2015-09-06
[1] => 2015-09-13
[2] => 2015-09-20
[3] => 2015-09-27
)
$result_sat = Array
(
[0] => 2015-09-19
)
So, why the difference is not occurring??
$result1 = array_diff($result_sun,$result_sat);
$result2 = array_diff($result_sat,$result_sun);
$result=array_merge($result1,$result2);
Compares $result_sun against one or more other arrays and returns the values in $result_sun that are not present in any of the other arrays.
so take difference of both and then merge it will be good if you put your code then we can give more accurate answer

comparing 2 arrays php

I am trying to compare two different arrays and get the values that do not exist in 1 of the arrays. Here are my 2 arrays:
Array ( [0] => 2fbd5868-28ec-418d-854a-0736db720c8a [1] => f4a41974-5373-4862-a5e7-9d28b8c2301f [2] => a1874f68-3da1-47c3-97ef-a68580ce2a52)
Array ( [0] => 2fbd5868-28ec-418d-854a-0736db720c8a [1] => f4a41974-5373-4862-a5e7-9d28b8c2301f [2] => a1874f68-3da1-47c3-97ef-a68580ce2a52 [3] => 583cee91-1913-4e9d-b51d-e27083420001)
As you can see the second array has an additional value. I am trying to user array_diff like this:
$result = array_diff($array1,$array2);
print_r($result);
However the out of the array_diff is:
array()
Any ideas what is going on?
As people have suggested and i have already tested switching the arrays around, this is the output:
Array ( [0] => [1] => )
array_diff gives you the values from $array1 that are not in the other arrays. All the values of your first array are in the second. Sou change the order of your arrays and you should be fine.
See also here: http://php.net/manual/de/function.array-diff.php
The order of arguments in array_diff() is important
Returns an array containing all the entries from array1 that are not
present in any of the other arrays2
Read array_diff
$result = array_diff($array2,$array1);
Try like this

Navigating a multidimensional array with dynamic

I'm trying to figure out why it is that I cannot access the follow array with this statement:
var_dump($thevar[0]['product_id']);
Array
(
[d142d425a5487967a914b6579428d64b] => Array
(
[product_id] => 253
[variation_id] =>
[variation] =>
[quantity] => 1
[data] => WC_Product Object
(
[id] => 253
[product_custom_fields] => Array
(
[_edit_last] => Array
(
[0] => 1
)
[_edit_lock] => Array
(
[0] => 1345655854:1
)
[_thumbnail_id] => Array
(
[0] => 102
)
I can, however, access the 'product_id' using the dynamically created array name:
print_r($thevar['d142d425a5487967a914b6579428d64b']['product_id']);
The issue is, I don't know what that dynamic name is going to be on the fly...
There are several options for such scenarios.
Manually iterate over the array
You can use reset, next, key and/or each to iterate over the array (perhaps partially).
For example, to grab the first item regardless of key:
$item = reset($thevar);
Reindex the array
Sometimes it's just convenient to be able to index into the array numerically, and a small performance hit is not a problem. In that case you can reindex using array_values:
$values = array_values($thevar);
$item = $values[0]; // because $values is numerically indexed
Iterate with foreach
This would work for a single value as well as it works for more, but it might give the wrong impression to readers of the code.
foreach($thevar as $item) {
// do something with $item
}
If the array key is dynamic you might find the PHP function array_keys() useful.
It will return an array of the keys used in an array. You can then use this to access a particular element in the array.
See here for more:
http://php.net/manual/en/function.array-keys.php
Because PHP array are associative therefor you have to access them by key.
But you may use reset($thevar) to get first item.
Or array_values():
array_values($thevar)[0]
Or if you feel like overkill you may also use array_keys() and use the [0] element to address element like this:
$thevar[ array_keys($thevar)[0]]

Categories