I have two queries:
1) $result = $this->_db->get_where("wishes",array("is_open"=>1))->result_array();
2) $requirements_result = $this->_db->get("requirements")->result_array();
I'm trying to output the data in this JSON format:
{
[
{
id:12,
title:"Meet Messi",
image_url:"http://dsadsa.dsadsa",
previewImageUrl:"http://kdjfla.com"
is_open:"true"
requirements: [
{
id: 123,
title:"kiss Messi",
is_complete: true
}
]
}
]
}
}
I created two models (one for each query).
This is what I've done so far:
$result = $this->_db->get_where("wishes",array("is_open"=>1))->result_array();
$requirements_result = $this->_db->get("requirements")->result_array();
$return_array = array();
foreach ($result as $value)
{
$wishes_model = new wishes_model();
$wishes_model->init_wishes($value);
$return_array[] = $wishes_model;
}
return $return_array;
How to i insert the requirements result to create this JSON?
First, create your wishes array as an associative array, with the ID as the key:
$wishes_array = array();
foreach ($results as $value) {
$wishes_model = new wishes_model();
$wishes_model->init_wishes($value);
$wishes_array[$value['id']] = $wishes_model;
}
Then you can add the requirements to the appropriate wish:
foreach ($requirements_results as $req) {
$wishes_array[$req['wish_id']]->requirements[] = $req;
}
I'm making some assumptions about which things in your application are associative arrays versus objects. You should be able to adjust this to match your specific implementation.
I have couple of question but for now i am gonna guess.
You can try array_merge but it will overwrite same keys.
If you don't want that you can add prefix to keys and then merge both array.
And i think rest of the solutions you already have in here.
Hi like you have 2 results say result1 and result2
you can make 2 foreach loop for each and store them in two different array and then
you make pass it in result and encode it.
see how it works:
foreach ($result1 as $res)
{
$result_s1[]=$res;
}
foreach($result2 as $cmd)
{
result_s1[]=$cmd;
}
$resultdata[]=array_merge($result_s1,$result_s2)
Related
In $data I have the following values:
Result
[{"id":2,"author":"example#mail.com","id_orders":502},
{"id":2,"author":"example#mail.com","id_orders":503},
{"id":2,"author":"example#mail.com","id_orders":505},
{"id":3,"author":"second-example#mail.com","id_orders":502},
{"id":3,"author":"second-example#mail.com","id_orders":503},
{"id":3,"author":"second-example#mail.com","id_orders":505},
{"id":4,"author":"third-example#mail.com","id_orders":502},
{"id":4,"author":"third-example#mail.com","id_orders":503},
{"id":4,"author":"third-example#mail.com","id_orders":505}]
I want unique results for id and id_orders. I want 3 out of these 9 results. I have tried this, but it helps on one id_orders condition.
PHP code
$result = json_decode($data, true);
$unique_array = [];
foreach($result as $element) {
$hash = $element['id_orders'];
$unique_array[$hash] = $element;
}
$data = array_values($unique_array);
Do you know how it can be different to make it work for two?
You can do it by keeping track of the values that were already used. Disclaimer: this solution will only produce a clear result for cases where the number of unique values for both criteria is the same.
$uniqueArray = [];
$usedValues = [
'id' => [],
'id_orders' => [],
];
foreach ($result as $element) {
if (!in_array($element['id'], $usedValues['id']) && !in_array($element['id_orders'], $usedValues['id_orders'])) {
$uniqueArray[] = $element;
$usedValues['id'][] = $element['id'];
$usedValues['id_orders'][] = $element['id_orders'];
}
}
Basically, what's happening here is that we're using $usedValues to store all the unique values we've already used and comparing against it using in_array. When we iterate through the objects, any object with an id or id_orders that has already been used will be skipped. The pairings will be done in order of appearance in the array.
I've gone an extra mile to try and make this code a bit more generic:
* Finds elements with a unique combination of values under given keys.
*
* Assumes all elements in the array are arrays themselves and that the
* subarrays have the same structure. Assumes subarray elements are not
* objects (uses strict comparison).
*/
function uniqueCombination(array $arrayToFilter, array $keysToFilterOn): array
{
if (empty($arrayToFilter) || empty($keysToFilterOn)) {
throw new \InvalidArgumentException(
'Parameters of uniqueCombination must not be empty arrays'
);
}
// get the keys from the first element; others are assumed to be the same
$keysOfElements = array_keys(reset($arrayToFilter));
$keysPresentInBoth = array_intersect($keysToFilterOn, $keysOfElements);
// no point in running the algorithm if none of the keys are
// actually found in our array elements
if (empty($keysPresentInBoth)) {
return [];
}
$result = [];
$usedValues = array_combine(
$keysPresentInBoth,
array_fill(0, count($keysPresentInBoth), [])
);
foreach ($arrayToFilter as $element) {
if (!isAlreadyUsed($usedValues, $element)) {
$result[] = $element;
foreach ($keysPresentInBoth as $keyToUse) {
$usedValues[$keyToUse][] = $element[$keyToUse];
}
}
}
return $result;
}
function isAlreadyUsed(array $usedValues, array $element): bool
{
foreach ($usedValues as $usedKey => $usedValue) {
if (in_array($element[$usedKey], $usedValue)) {
return true;
}
}
return false;
}
In its core, this is the same algorithm, but made dynamic. It allows a variable number of keys to filter on (that's why they're passed separately as an argument), so the $usedValues array is created dynamically (using the first element's keys as its own keys, filled with empty arrays) and all the keys must be compared in loops (hence the separate function to check if an element's value had already been used).
It could probably be tweaked here or there as I haven't tested it thoroughly, but should provide satisfactory results for most structures.
This is how I used to create keys that didn't exist inside an array when looping through data:
$array = [];
foreach ($results as $result) {
if (!isset($array[$result->id])) {
$array[$result->id] = [];
}
$array[$result->id][] = $result->value;
}
A colleague at work does the following. PHP doesn't error but I am not sure if it's a feature of PHP or if it's incorrect:
$array = [];
foreach ($results as $result) {
$array[$result->id][] = $result->value;
}
Is it incorrect for me to do the above?
if condition you put in your code is unnecessary. Let me explain.
if (!isset($array[$result->id])) {
$array[$result->id] = [];
}
This mean if $array[$result->id] is not exist than you are define it as an array, however $array[$result->id][] it self create new array if not existing without throwing any error. So no need to use if condition error. In conclusion, both code are correct, just you are using unnecessary if condition.
I have a JSON file. (Steam API). I want to display player inventory in my website. I use this url: https://steamcommunity.com/id/majidsajadi/inventory/json/730/2
Then I decode it with json_decode function.
Now there are two arrays: rgInventory and rgDescription. I need to check if class id in rgInventory and classid in rgDescription match I use some of values in igDescription.
So I think I should use 2 foreach loop and a if condition to check if class id match. then I echo out the information I need.
The question is how should I use nested foreach?
You can use two nested foreach loops like this:
Assuming that $decoded_data is your decoded data after applying json_decode() function on the end result, like this: $decoded_data = json_decode($your_json_data, true);
foreach($decoded_data['rgInventory'] as $arr1){
foreach($decoded_data['rgDescriptions'] as $arr2){
if($arr1['classid'] == $arr2['classid']){
// both the classid matches
// your code
}
}
}
Try this code:
$steamData = json_decode(file_get_contents("https://steamcommunity.com/id/majidsajadi/inventory/json/730/2"), true);
if($steamData["success"] != 1){
exit();
}
$match = array();
foreach($steamData["rgInventory"] as $v1){
$match[$v1["classid"]]["match"] = false;
$match[$v1["classid"]]["count"] = 0;
}
foreach($steamData["rgDescriptions"] as $v2){
if(array_key_exists($v2["classid"],$match)){
$match[$v2["classid"]]["match"] = true;
$match[$v2["classid"]]["count"]++;
}
}
print_r($match);
I am doing laravel project. I have one sql query as,
$catcount=2;
for($i=0;$i<$catcount;$i++) {
$subCat[] = Category::where('parent_id', '=', $userCategory[$i])->pluck('id');
}
$subCat returns an array as,
[[54,55,56,57,58],[48,49,50,51,52]]
I want this array as a single dimensional array like,
[54,55,56,57,58,48,49,50,51,52]
I am not getting how to do this, Please help and thanks in advance.
I suggest You to do ids merge before querying, so You will save some run time by accessing database only one time.
$catcount = 2;
$parents_ids = [];
for ($i = 0; $i < $catcount; $i++) {
$parents_ids[] = $userCategory[$i];
}
$subCats = Category::whereIn('parent_id', $parents_ids)->pluck('id');
$catcount=2;
for($i=0;$i<$catcount;$i++) {
$subCat[] = Category::where('parent_id', '=' $userCategory[$i])->pluck('id');
}
array_merge($subCat[0],$subCat[1]);
From your final array, you can just do an array merge
list($a1, $a2) = $subCat;
$subCat = array_merge($a1, $a2);
There are a lot of ways to do that. One of them: simple, but universal, readable and updatable (if something will change in your data structure, you'll be able to update this code in no time):
$newArr = [];
foreach ($subCat as $subArr) {
foreach ($subArr as $value) {
$newArr[] = $value;
}
}
if your array have multiple elements, you can merge them using this code:
$subCats = call_user_func_array("array_merge", $subCat);
Problem:
Extract data from an object/array and represent this data using a multidimensional array with a unique key generated from the inner loop.
I always find myself building multidimensional arrays like this:
$final_array = array();
foreach ($table as $row) {
$key = null;
$data = array();
foreach ($row as $col => $val) {
/* Usually some logic goes here that does
some data transformation / concatenation stuff */
if ($col=='my_unique_key_name') {
$key = $val;
}
$data[$col] = $val;
}
if (!is_null($key) {
if (!isset($final_array[$key]) {
$final_array[$key] = array();
}
$final_array[$key][] = $data;
}
}
I can't help but wonder if I'm constantly doing this out of habit, but it feels kind of verbose with all the key-checking and whatnot. Is there a native function I am not utilizing? Can this be refactored into something more simple or am I overthinking this?
Why are you always doing that? Doesn't seem the common kind of stuff one works with on a day to day basis... Anyway, that's kinda cryptic (an example would be nice) but have you though of using an MD5 hash of the serialized dump of the array to uniquely define a key?
$key = md5(serialize($value));