Php merge object array getting wrongly only merge last values - php

I am trying to merge an object as follows from set of values which comes from database as follows:
$pooldetails = array();
$qstncount = 5;
for($i=0;$i<$qstncount;$i++){
$stdClass = $DB->get_record_sql("SELECT * FROM {pool_objective} po WHERE (po.id = $randarray[$i])");
$pooldetails = (object) array_merge((array) $pooldetails, (array) $stdClass);
}
When I print outside as follows:
print_r($pooldetails);
I am getting only last value in this array. I mean the value of $qstncoun=4 .First 4 values are missing.What I am doing wrong?

It's expected actually. Quoting the docs:
If the input arrays have the same string keys, then the later value
for that key will overwrite the previous one.
To get the results combined, use array_merge_recursive() instead:
$arr1 = ['a' => 1];
$arr2 = ['a' => 2];
var_dump(array_merge($arr1, $arr2));
// ['a' => 2]
var_dump(array_merge_recursive($arr1, $arr2));
// ['a' => [1, 2]]
Be aware, however, of the following:
If the input arrays have the same string keys, then the values for
these keys are merged together into an array, and this is done
recursively, so that if one of the values is an array itself, the
function will merge it with a corresponding entry in another array
too. If, however, the arrays have the same numeric key, the later
value will not overwrite the original value, but will be appended.
It probably doesn't matter in your case, however, as keys map to column names. So you can use something like...
$pooldetails = array();
$qstncount = 5;
for($i=0;$i<$qstncount;$i++){
$stdClass = $DB->get_record_sql("SELECT * FROM {pool_objective} po WHERE (po.id = $randarray[$i])");
$pooldetails = array_merge_recursive($pooldetails, (array) $stdClass);
}
$pooldetails = (object) $pooldetails;

Related

Keep duplicate keys in array

I am getting data from whois and breaking the data up and putting it into an array with keys but some need multiple keys the same name is there anyway i can add number onto the end of the same named keys to make them unique?
here is my code so far
$test1 =$check_domain->find_whois_details("be.co");
$rows = explode("\n", $test1);
$arr = array('info'=>"");
foreach($rows as $row) {
$posOfFirstColon = strpos($row, ":");
if($posOfFirstColon === FALSE)
$arr['info'] .= $row;
else
$arr[substr($row, 0, $posOfFirstColon)] = trim(substr($row, $posOfFirstColon+1));
}
$a = array_map('trim', array_keys($arr));
$b = array_map('trim', $arr);
$arr = array_combine($a, $b);
print($arr["Registry Expiry Date"]);
It seems like a more manageable solution would be to change your storage structure to a multidimensional array rather than a flat array.
$arr[substr($row, 0, $posOfFirstColon)][] = trim(substr($row, $posOfFirstColon+1));
In this structure, each name would correspond to an array containing one or more values. This way, the key retains its original value, which would become less meaningful if you appended some arbitrary value to it to keep it unique.
This may not work for your specific scenario, but it's generally a better representation for grouping a set of data by a specific property.
bool array_key_exists ( mixed $key , array $array )
array_key_exists — Checks if the given key or index exists in the array
<?php
$search_array = array('first' => null, 'second' => 4);
// returns true
array_key_exists('first', $search_array);
?>
Using this function, you can check if the key is already existing, in that case just concatenate a number after the key you're inserting !

How to get the exact value of the last array index in PHP?

Currently i have an array $newArr with some elements as shown in picture below. How do I know the last digit of the array index (highlighted in yellow)?
This is important because, if later I wanted to insert a new record into this $newArr array, I could just
$newArr[$the_variable_that_holds_the_last_digit + 1] = ['foo', 'bar'];
otherwise the whole array overwrite if
$newArr = ['foo', 'bar'];
I think you are looking for end pointer
$array = array(
'a' => 1,
'b' => 2,
'c' => 3,
);
end($array); // it will point to last key
$key = key($array); // get the last key using `key`
Assuming you have the numerically indexed array, the last index on your array is :
$last_index = count($newArr) -1;
if However your keys are not sequential, you can do this:
end($newArr);
$last_key = key($newArr);
I think you can try this
$array = end($newArr);
$last_index = key($array);//Its display last key of array
For more details, please follow this link.
If the only reason is to not overwrite the values you can use [] which means add new value.
$arr = [1,2,3,4];
var_dump($arr);
// incorrect way:
$arr = [1,2];
var_dump($arr);
//correct way
$arr = [1,2,3,4];
$arr[] = [1,2];
var_dump($arr);
See here for output: https://3v4l.org/ZTg28
The "correct way" will in the example above input a new array in the array.
If you want to add only the values you need to insert them one at the time.
$arr[] = 1;
$arr[] = 2;

PHP get part of string to new array?

If I have an array in the following format, how can I assign part of these array values in to a new array?
(Numeric value 123 and 654 indicate that the array can be separated in these locations)
$fruits = array();
$vehicles = array();
$all_words = array ("123", "apple", ”orange”, ………, ”bannana”, ”123”, ”654”, ”car”, ”bus”, ………, ”train”, ”bike”, ”654”);
//continuous ……… Indicate there can be unknown amount of array elements.
//Also, these numeric values of 123 and 645 can be changed to something convenient
I can see that using $fruits = array_slice($array, 1, 5) I can get a portion of this array in to a new one. But if I don’t know the length of array between two numbers(123 and 654, how can I assign these values in to an new array?
You can get their index using array_search() and then use them for slicing, like this..
$index1 = array_search('123', $all_words);
$index2 = array_search('654', $all_words);
$vehicles = array_slice($array, $index1, $index2-$index1+1);
$fruits = array_slice($array, array_search('123', $array)+1, array_search('654', $array)+1)

PHP make N copies of array with functions

In my code I need to make a number of copies of a dummy array. The array is simple, for example $dummy = array('val'=> 0). I would like make N copies of this array and tack them on to the end of an existing array that has a similar structure. Obviously this could be done with a for loop but for readability, I'm wondering if there are any built in functions that would make this more verbose.
Here's the code I came up with using a for loop:
//example data, not real code
$existingArray = array([0] => array('val'=>2),[1] => array('val'=>3) );
$n = 2;
for($i=0;$i<$n;$i++) {
$dummy = array('val'=>0); //make a new array
$existingArray[] = $dummy; //add it to the end of $existingArray
}
To reiterate, I'd like to rewrite this with functions if such functions exist. Something along the lines of this (obviously these are not real functions):
//make $n copies of the array
$newvals = clone(array('val'=>0), $n);
//tack the new arrays on the end of the existing array
append($newvals, $existingArray)
I think you're looking for array_fill:
array array_fill ( int $start_index , int $num , mixed $value )
Fills an array with num entries of the value of the value parameter, keys starting at the start_index parameter.
So:
$newElements = array_fill(0, $n, Array('val' => 0));
You do still have to handle the appending of $newElements to $existingArray yourself, probably with array_merge:
array array_merge ( array $array1 [, array $... ] )
Merges the elements of one or more arrays together so that the values of one are appended to the end of the previous one. It returns the resulting array.
If the input arrays have the same string keys, then the later value for that key will overwrite the previous one. If, however, the arrays contain numeric keys, the later value will not overwrite the original value, but will be appended.
Values in the input array with numeric keys will be renumbered with incrementing keys starting from zero in the result array.
So:
$existingArray = array_merge($existingArray, $newElements);
This all works because your top-level arrays are numerically-indexed.

str_replace() and strpos() for arrays?

I'm working with an array of data that I've changed the names of some array keys, but I want the data to stay the same basically... Basically I want to be able to keep the data that's in the array stored in the DB, but I want to update the array key names associated with it.
Previously the array would have looked like this: $var_opts['services'] = array('foo-1', 'foo-2', 'foo-3', 'foo-4');
Now the array keys are no longer prefixed with "foo", but rather with "bar" instead. So how can I update the array variable to get rid of the "foos" and replace with "bars" instead?
Like so: $var_opts['services'] = array('bar-1', 'bar-2', 'bar-3', 'bar-4');
I'm already using if(isset($var_opts['services']['foo-1'])) { unset($var_opts['services']['foo-1']); } to get rid of the foos... I just need to figure out how to replace each foo with a bar.
I thought I would use str_replace on the whole array, but to my dismay it only works on strings (go figure, heh) and not arrays.
The idea:
Get a list of all your array keys
Modify each one of them as you choose
Replace the existing keys with the modified ones
The code:
$keys = array_keys($arr);
$values = array_values($arr);
$new_keys = str_replace('foo', 'bar', $keys);
$arr = array_combine($new_keys, $values);
What this actually does is create a new array which has the same values as your original array, but in which the keys have been changed.
Edit: updated as per Kamil's comment below.
For the values you've provided
$var_opts['services'] = array('foo-1', 'foo-2', 'foo-3', 'foo-4');
var_dump($var_opts['services']);
foreach($var_opts['services'] as &$val) {
$val = str_replace('foo', 'bar', $val);
}
unset($val);
var_dump($var_opts['services']);
or if you want to change the actual keys
$var_opts['services'] = array('foo-1' => 1, 'foo-2' => 2, 'foo-3' => 3, 'foo-4' => 4);
var_dump($var_opts['services']);
foreach($var_opts['services'] as $i => $val) {
unset($var_opts['services'][$i]);
$i = str_replace('foo', 'bar', $i);
$var_opts['services'][$i] = $val;
}
var_dump($var_opts['services']);

Categories