I'm trying to add one array values with existing array values ,but i'm stuck how to add them
Array-1
[main] => Array
(
[0] => stdClass Object
(
[clientID] => 2
[maintenance_due] => 2016-05-09 00:00:00
[complete_maintenance] => 1
[description] => dfdff
[created_at] => 2016-05-01 00:00:00
[completed_on] => 2016-05-06 00:00:00
[name] => Bottel packing
[type_id] => 1
[machinecode] => HITBTP001
[model_no] => ModelA
[created_date] => 2016-03-27 06:55:05
[updated_date] => 0000-00-00 00:00:00
)
)
Array-2
[dt] => Array
(
[dtm] => 0
[edm] => 1
)
I want like this
[main] => Array
(
[0] => stdClass Object
(
[clientID] => 2
[maintenance_due] => 2016-05-09 00:00:00
[complete_maintenance] => 1
[description] => dfdff
[created_at] => 2016-05-01 00:00:00
[completed_on] => 2016-05-06 00:00:00
[name] => Bottel packing
[type_id] => 1
[machinecode] => HITBTP001
[model_no] => ModelA
[created_date] => 2016-03-27 06:55:05
[updated_date] => 0000-00-00 00:00:00
[dtm] => 0
[edm] => 1
)
)
I'm trying array_push function and also use foreach but isn't working .
Please suggest how can i do this.
The solution using array_merge function and conversion(casting) from array into object and vice versa(only for basic stdClass objects):
// $array1 is your first array with 'main' key
// $array2 is your second array with 'dt' key
$main_arr = (array) current($array1['main']); // converting object into array
$merged = array_merge($main_arr, $array2['dt']); // combining "properties"
$array1['main'] = [(object) $merged]; // saving object with additional properties back to the initial array
print_r($array1); // will give the expected output
[0] => stdClass Object
What you have under index 0 is not an array, but object. Unless it implements ArrayAccess interface, you cannot do this as you'd with regular array.
More on Objects: https://secure.php.net/manual/en/language.types.object.php
Assuming $big_array is the first array you posted and $small_array is the second array you posted then this should work:
$big_array['main'][0] = (object)array_merge((array)$big_array['main'][0], $small_array['dt']);
I dunno what your code looks like so this one might work automatically for you:
$main[0] = (object)array_merge((array)$main[0], $dt);
Per Marcin Orlowski's comment, below is the proper way to do this without the risk of overriding any classes or methods:
$main[0]->dtm = $dt['dtm'];
$main[0]->edm= $dt['edm'];
Related
I have an existing array, and I want to add some items in it from a mysql row
$extendedadmindetails = full_query("SELECT * FROM `tbladmins` WHERE `id`='{$_SESSION['adminid']}'");
$extendedadmindetailsrow = mysql_fetch_assoc ($extendedadmindetails);
array_push($apiresults, $extendedadmindetailsrow);
This returns an array in an array:
Array
(
[result] => success
[adminid] => 1
[name] => My Name
[notes] =>
[signature] =>
[allowedpermissions] => My Name
[departments] => 1
[requesttime] => 2017-02-26 12:44:06
[0] => Array
(
[id] => 1
[uuid] => sqdqsdqsdqsdq454
[roleid] => 1
[username] => Myname
[password] => $dfsdfsdfsdfsdfsdfsdfsdfsdfsdfsdfsdf
[passwordhash] => $jghjghjghjghjghjghjghjghjg
[updated_at] => 0000-00-00 00:00:00
)
)
while I need:
Array
(
[result] => success
[adminid] => 1
[name] => My Name
[notes] =>
[signature] =>
[allowedpermissions] => My Name
[departments] => 1
[requesttime] => 2017-02-26 12:44:06
[id] => 1
[uuid] => sqdqsdqsdqsdq454
[roleid] => 1
[username] => Myname
[password] => $dfsdfsdfsdfsdfsdfsdfsdfsdfsdfsdfsdf
[passwordhash] => $jghjghjghjghjghjghjghjghjg
[updated_at] => 0000-00-00 00:00:00
)
I believe I should use array_push to add to an existing array, but I'm not sure how to proceed from there. Do I need to loop trough the extendedadmindetailsrow array and add items 1 by 1?
Any one can help me out with this?
Thanks!!
use of array_merge is better in case
// Considering your mysql is returning only 1 row
foreach ($extendedadmindetailsrow as $key => $row) {
$arr = $row;
}
// after this if you will try array_push also that will work
$result = array_merge($apiresults, $arr);
print_r($result);
Take a look at array_merge
array_merge($apiresults, $extendedadmindetailsrow);
You can:
$result = $apiresults + $extendedadmindetailsrow;
Use array_merge()
$a1=array("red","green");
$a2=array("blue","yellow");
print_r(array_merge($a1,$a2));
Output will be
Array (
[0] => red
[1] => green
[2] => blue
[3] => yellow
)
I have an array which has changing key depending on the table and it can also have custom fields added. I want to be able to identify if the array contains any values that are dates and then format the date.
I have used two examples here, but they keys could be anything and the dates could be including date and/or time. The language I am using in my app is PHP5.5.
Any ideas?
Array
([0] => Array (
[id] => 1
[filename] => 1051404995566.png
[createdby] => 1
[createddate] => 2014-07-10 13:32:46
[enddate] => 2014-07-10
)
[1] => Array (
[id] => 2
[filename] => 1561404995587.png
[createdby] => 1
[createddate] => 2014-07-10 13:33:07
[enddate] => 2014-08-01
)
)
I have an array of data returned from the eventbrite.com api stored in a variable called $restrictedEvents which looks like the data below. This is representative of just one event for the purposes of pasting here but it has a about 80 stdClass Objects like this in the full array.
I want to sort this array alphabetically by the [title] key in each stdClass Object. I have tried using:
usort($restrictedEvents, "title");
However this returns the following error:
Warning: usort() [function.usort]: Invalid comparison function in model.php on line 109
My guess is it cannot find the title key as this is in the next level down. Any pointers on where I am going wrong and how I can sort by the title would be greatly appreciated. Many thanks.
Array
(
[4791063199] => stdClass Object
(
[box_header_text_color] => 393837
[link_color] => EE6600
[box_background_color] => FFFFFF
[box_border_color] => D9D4D0
[timezone] => Europe/London
[organizer] => stdClass Object
(
[url] => http://www.eventbrite.com/org/2866607767
[description] =>
[long_description] =>
[id] => 2866607767
[name] => B&Q Manifestival
)
[background_color] => E3DFDC
[id] => 4791063199
[category] =>
[box_header_background_color] => F0ECE9
[capacity] => 20
[num_attendee_rows] => 0
[title] => Closed Event Test
[start_date] => 2012-11-07 19:00:00
[status] => Live
[description] => Lorem ipsum
[end_date] => 2012-11-07 21:00:00
[tags] =>
[timezone_offset] => GMT+0000
[text_color] => 393837
[title_text_color] =>
[password] =>
[tickets] => Array
(
[0] => stdClass Object
(
[ticket] => stdClass Object
(
[description] =>
[end_date] => 2012-11-07 17:00:00
[min] => 1
[max] => 1
[price] => 0.00
[quantity_sold] => 0
[visible] => true
[currency] => GBP
[quantity_available] => 20
[type] => 0
[id] => 15940001
[name] => Manifestival Event
)
)
)
[created] => 2012-11-07 10:40:36
[url] => http://www.eventbrite.com/event/4791063199
[box_text_color] => 393837
[privacy] => Private
[venue] => stdClass Object
(
[city] =>
[name] => HR Training Room
[country] =>
[region] =>
[longitude] => 0
[postal_code] =>
[address_2] =>
[address] =>
[latitude] => 0
[country_code] =>
[id] => 2619469
[Lat-Long] => 0.0 / 0.0
)
[modified] => 2012-11-07 10:47:20
[repeats] => no
)
The second paramater to usort should be a function. See http://php.net/manual/en/function.usort.php. You would need to pass it a function like:
function cmp($a, $b)
{
return strcmp($a->title, $b->title);
}
I think you would then call it like usort($restrictedEvents, "cmp");.
You can do it with ouzo goodies:
$result = Arrays::sort($restrictedEvents, Comparator::compareBy('title'));
http://ouzo.readthedocs.org/en/latest/utils/comparators.html
The second parameter to usort is a function, not a key name. The function gets passed two elements of the array being sorted and returns a value indicating how those two elements should be ordered with respect to each other: -1 if the order in which they're passed to the function is correct, 1 if it's reversed, and 0 if it doesn't matter (the two elements are equal as far as the comparison goes). Here's an example for your case:
usort($restrictedEvents,
function($a, $b) { return strcmp($a->title, $b->title); });
If you're on an older PHP (before 5.3.0, which introduced anonymous functions), then you have to give the comparison function a name and pass that name as a string to usort:
function titlecmp($a, $b) {
return strcmp($a->title, $b->title);
}
usort($restrictedEvents, "titlecmp");
Usually something like this is achieved via a second array with $keyToSort => $id, sort this array via the standart sort functions or your own, then you have a conversion to your first array
using this, the depth of your array is limitless.
I have a PHP array containing movie descriptions ($descriptions) and another PHP array containing showtimes and ticket quantities ($stock) for those movies. For each unique movie ID in $descripctions, I need to get all of the showtimes and tickets from $stock.
Is there no built-in PHP function that will search for the unique ID and return the chain of keys needed to access that value? I can't find an elegant solution after a full day of Googling and reviewing every array function in the PHP manual twice.
If there's no more elegant solution, is my best approach a custom recursive function? If so, any guidance on best approach / control structure? Maybe counting array elements and using several levels of while loops to go through each level of the array?
Here's the beginning of the $stock array I'm trying to get the data from -- won't post the entire print_r() because the source array is over 67,000 lines long but this much should indicate the structure I'm working with.
Thank you very much!!!
Array (
[products] => Array (
[venue] => Array (
[0] => Array (
[title] => 3-D Digital Cinema
[length] => 25
[memberonly] => 0
[shows] => Array (
[show] => Array (
[0] => Array (
[title] => Planet You
[location] => 3-D Digital Cinema
[eventnumber] => 521
[date] => Array (
[0] => Array (
[eventdate] => 2012/01/01
[times] => Array (
[time] => Array (
[0] => Array (
[starttime] => 13:00:00
[instock] => 110
)
[1] => Array (
[starttime] => 16:00:00
[instock] => 110
)
)
)
)
[1] => Array (
[eventdate] => 2012/01/02
[times] => Array (
[time] => Array (
[0] => Array (
[starttime] => 13:00:00
[instock] => 110
)
[1] => Array (
[starttime] => 16:00:00
[instock] => 110
)
)
)
)
For the life of me I can not figure out how to access the values of this array. Every example the stdClass Object has some type of value. If I try for example $obj->0->0->city; I get an error.
Can someone show me a example how to access [city] => toronto or even [date_created] => 2011-05-03 14:33:58?
I also tried this with no luck.
$object = $buy[1];
$title = $object->title[0];
echo "$title";
Thanks
This is what the api gives me.
stdClass Object
(
[id] => 1
[name] => toronto
[date_modified] => 2011-03-08 13:07:10
[tax_rate_provincial] =>
)
<br/>
Array
(
[0] => stdClass Object
(
[0] => stdClass Object
(
[id] => 28131844
[full_date] => 20110506
[end_date] => 20110511
[city] => toronto
[saved] => 1651
[discount_percentage] => 52
[deal_option] => Array
(
[0] => stdClass Object
(
[id] => 2600
[title] =>
[date_modified] => 0000-00-00 00:00:00
[date_created] => 2011-05-03 14:33:58
[value] => 3150
[price] => 1499
[deal_id] => 28131844
[is_default] => 0
)
)
[options] =>
[option_quantity] =>
[option_remaining] =>
[purchase_limit] => 1
[gift_limit] => 0
There is a special evil syntax to bypass numeric object attributes:
print $obj->{'0'}->{'0'}->city;
Is the correct syntax, and equivalent to the path you already determined.
Your second example is an array however, so it's probably:
print $array[0]->{'0'}->city;
The alternative is always to just foreach over a specific level - that works for objects and arrays likewise.