Push value to array - php

I have an array with multiple values and need to push a value into this array.
The orignial array looks like:
[0]=> array(2) { ["name"]=> string(17) "Name" ["id"]=> string(8) "134567" }
[1]=> array(2) { ["name"]=> string(13) "Name" ["id"]=> string(9) "123456" }
And I need to put these values into the above array:
$personal['id']
$personal['name']
How can this be done?

Use square bracket notation to append to the original array:
$original[] = $person;
Or if $person is more complex and you only want those two keys:
$original[] = array(
'name' => $personal['name'],
'id' => $personal['id']);

Assuming that the $personal array only contains id and name you could use array_push.
array_push($array, $personal);

Seems that the guy who gave me the answer deleted his answer,
But this I used to add values to
$originalArray[]['id'] = $personal['id'];
$originalArray[]['name'] = $personal['name'];
Anyway ++1 for you, thanks! :)

See if this works for you:
$yourarray[]=$personal;

Related

Php sorting multidimensional array?

How to sort the following array?
I have an multidimensional array that gets filled with total hours for each brand
$totalHours = array(
'brand' => array(),
'project' => array(),
'hours' => array()
);
The output is something like this (project is not filled):
array(3) {
["brand"]=>
array(3) {
[0]=>
string(4) "Nike"
[1]=>
string(9) "Coke Cola"
[2]=>
string(8) "Converse"
}
["project"]=>
array(3) {
[0]=>
string(6) "Bonobo"
[1]=>
string(4) "LDRU"
[2]=>
string(2) "US"
}
["hours"]=>
array(3) {
[0]=>
int(28)
[1]=>
int(106)
[2]=>
string(1) "2"
}
}
Now I would like to sort the array based on the "hours" field.
I've tried the array_multisort but it seems like I simply don't get how this function works and how to apply it to this array.
I have been able to sort an single array with just one row of values. If I apply that to this problem im sorting only the hours field, leaving the others unsorted and therefore the array is corrupted.
The "project" does actually contains a string. It always does. In this example I didn't filled it.
array_multisort should work:
$totalHours = array(
'brand' => array('Nike', 'Coke Cola', 'Converse'),
'project' => array(),
'hours' => array(28, 106, '2')
);
array_multisort($totalHours['hours'], $totalHours['brand']);
var_dump($totalHours);
That data format is not very convenient because there is no direct association between brands and hours, they even sit in different arrays! Plus, the last hour is a string, not an integer.
We're going to have to create an intermediate array to associate them and sort them. We'll then re-inject everything in the original array.
// Make sure both arrays of brands and hours and the same size
if (count($totalHours['brand']) != count($totalHours['hours'])) {
throw new Exception('Invalid data!');
}
// Make sure every hour record is an integer, not a string
$totalHours['hours'] = array_map('intval', $totalHours['hours']);
// array_combine will sort all arrays based on the sorting of the first one
array_multisort($totalHours['hours'], $totalHours['brand'], $totalHours['project']);
EDIT: Using array_multisort was #delprks 's idea originally. Here I applied it to both brand and project arrays.
You cant do that with a single array_* function!
if (project is not filled) always and the indexes of brand and hours are equal, then you can do:
$forsort = array_combine($totalHours["brands"],$totalHours["hours"]);
asort($forsort,SORT_NUMERIC);
$totalHours["brands"]=array_keys($forsort);
$totalHours["hours"]=array_values($forsort);
But, this is just an answer for you question, not best practise at all.

Associative Array get key value in PHP

array(24) { ["user_id"]=> string(1) "9" ["facebook_id"]=> string(15) "381305418721463" ["first_name"]=> string(4) "John" ["last_name"]=> string(4) "Does" ["current_latitude"]=> string(10) "-37.825697" ["current_longitude"]=> string(10) "144.999965" ["current_address"]=> string(45) "229 Swan Street, Richmond VIC 3121, Australia" ["date_of_birth"]=> string(10) "01/01/1990" ["city"]=> string(30) "Melbourne, Victoria, Australia" ["country"]=> string(0) "" ["email_address"]=> string(22) "bzingatester#gmail.com" ["profile_pic"]=> string(0) "" ["first_login"]=> string(2) "no" ["blocked_users_id"]=> string(0) "" ["my_friend"]=> string(52) "10152805813948795,10155307822515151,1389504958030240" ["search_radius"]=> string(2) "50" ["device_type"]=> string(3) "ios" ["device_id"]=> string(1) "1" ["device_token"]=> string(64) "6ddaf9d59418e99b1c9cb28c21d94647bfed9f78a80b410164c1f2798beee84a" ["hideFromActivityFeed"]=> string(2) "no" ["hideFromFriendsofFriends"]=> string(2) "no" ["hideNotification"]=> string(2) "no" ["created_date"]=> string(19) "2015-01-07 01:00:11" ["modified_date"]=> string(19) "2015-02-27 05:36:12" }
In PHP I have an array called $userData as per above, I want to be able to echo values such as first name 'first_name', using code like this
echo $userInfo->first_name;
(this doesnt seem to work)
I DO NOT want to loop and fetch all keys in array using foreach, just get values 'first_name', 'last_name' ect. from the array
Please try like this,
$first_name = $userInfo['first_name'] // $userInfo is array name
You can change the array to object and then use -> like below
$userData= (object) $userData;
And then
$userData->firstName ..etc
Please use type casting.
$userinfo = (array)$userInfo;
Then you access your key first_name.
echo $userinfo['first_name'];
First of use a different method to dump data ..
echo "<pre>";
print_r($your_array);
exit;
It just simply bodes for a better presentation to see what is an object and what is an array.
You cannot access array members with the object notation. You can however cast your array as an object.
(object)$yourarray;
If you want to access array members, use :
$yourarray['first_name'];
If you cast as an object:
$obj = (object)$yourarray;
Now access:
$obj->firstname;
Hope that helps.
Actually we use arrays in programming to prevent loop or something like this to find a value, so instead of this structure,
$a = 'text1';
$b = 0;
$c = true;
$d = 'text2';
we use arrays:
$array = array('a' = > 'text1', 'b' => 0, 'c' => true, 'd' => 'text2' );
and to access the value of some key, we call the key name, inside brackets after array's name:
echo $array['a'];
//will echo text1
//or
echo $array['b'];
//will echo true
This is associative array...
if you just pass values to an array without keys, php will use numeric keys instead...
$array = array( 'text1', '0', true, 'text2' );
$array[0] = 'text1';
$array[1] = 0;
$array[2] = true;
$array[3] = 'text2';

What kind of Array is this and how do I use the data?

I'm using a Gravity Forms to create a form but want to do something extra with the data after submission of the form.
I'm using var_dump($_POST); to see what the resulting information that is sent is and I get this:
array(12) { ["input_1"]=> string(8) "John Doe" ["input_2"]=> string(11) "Some School" ["input_3"]=> string(8) "Any City" ["input_4"]=> string(7) "Alabama" ["input_5"]=> string(3) "456" ["is_submit_18"]=> string(1) "1" ["gform_submit"]=> string(2) "18" ["gform_unique_id"]=> string(0) "" ["state_18"]=> string(60) "WyJhOjA6e30iLCI5ZTU3ZGE4Mjk1MjFkYjg3MzRlNGQ5MzZjN2E5OWU1MiJd" ["gform_target_page_number_18"]=> string(1) "0" ["gform_source_page_number_18"]=> string(1) "1" ["gform_field_values"]=> string(0) "" }
I'm not familiar with this, yet (I learn so much from all of your help) how would I use, for example, the result from ["input_5"]?
Thank you in advance.
Do you mean this? echo $_POST['input_5'];
$_POST is an associate array, meaning that it is a container for multiple values (array) with named keys (associative). A numeric array doesn't have key names, and looks up values by index instead.
Associate Array - use this to store data that intuitively should be named and order does not matter
$myArr = [
'Name' => 'John Doe',
'Address' => '000 Some St.',
'Phone' => '000-0000'
];
$myArr['Address'];
//or
$key = 'Address';
$myArr[$key]; //use a variable as a key
Numeric Array - use this to store the same type of data where order matters
$myArr = [a,b,c,d,e,f,g];
$toDo = [
'Go to the store',
'Buy Eggs',
'Make Breakfast',
'Be Happy'
];
$myArr[0] //"a"
$toDo[1] //"Buy Eggs"

How to store 2 dependent values into an array?

I want to store 2 dependent values in this array:
["STEP5"]=> array(1) {
["OPTIONS"]=>
array(2) {
[0]=>
string(4) "opt2"
[1]=>
string(4) "opt3"
} }
Option fields (opt1, opt2,...) can have an extra field input. So how to store that in my array ? Thanx a lot.
You make each element of the OPTIONS array into an array itself. This would be better illustrated as:
["STEP5"] => array(1) {
["OPTIONS"] => array(2) {
[0] => array(2) {
["TEXT"] => "opt2"
["INPUT"] => "input data"
}
[1] => array(1) {
["TEXT"] => "opt3"
// No input data here
}
}
}
Then you can access the fields as:
$foo["STEP5"]["OPTIONS"][0]["TEXT"]
$foo["STEP5"]["OPTIONS"][0]["INPUT"]
$foo["STEP5"]["OPTIONS"][1]["TEXT"]
You don't have to have the "INPUT" field for every single option, but you can add it if you need to. Also, you might consider using objects to accomplish this task as they provide lots of useful functionality.

Push Associate array into another array

I would like to push an associate array into another array but I an not sure how to go about it. At the minute I have the following:
$rate_info = array(
"hotel_rating" => $hotel->{'hotelRating'},
"room_rate" => $hotel->{'RoomRateDetailsList'}->{'RoomRateDetails'}->{'RateInfo'}->{'ChargeableRateInfo'}->{'#total'},
"currency" => $hotel->{'RoomRateDetailsList'}->{'RoomRateDetails'}->{'RateInfo'}->{'ChargeableRateInfo'}->{'#currencyCode'},
"deep_link" => $hotel->{'deepLink'}
);
array_push($hotel_array[$hotel->{'name'}]["offers"], "expedia" => $rate_info );
"Offers" is an array , all I want to do is add an key value with an array within in. Any ideas? All I seem to be getting at the minute is parse errors.
UPDATE
This is the output of the array so far
["offers"]=>
array(2) {
["LateRooms"]=>
array(4) {
["hotel_rating"]=>
int(4)
["room_rate"]=>
string(6) "225.06"
["currency"]=>
string(3) "USD"
}
[0]=>
string(4) "test"
}
As you can see instad of [0] I would like ["site"]=>array()
Thanks
Oliver
I'd do this for the array assignment:
$hotel_array[$hotel->name]['offers']['expedia'] = $rate_info;
Ensure your warnings are enabled, so you know arrays (and subarrays) have been set up before you use them.
Did you first do this?
$hotel_array[$hotel->{'name'}] = array();
And then you can do:
array_push($hotel_array[$hotel->{'name'}]["offers"], "expedia" => $rate_info );

Categories