please excuse if this question is already answered elsewhere, but I just don't know what to search for, since I usually don't work with php.
I've got the following array:
(
[0] => Array
(
[login] => name23
[id] => 12356
)
[1] => Array
(
[login] => name12
[id] => 12345
)
[2] => Array
(
[login] => name34
[id] => 12367
)
)
And I'd like to only print the login-names, so in this example name23, name12, name34 (But I never know how many there are).
I've tried several approaches with foreach, which didn't work.
What is working, but only for one username is this:
echo $contributors[0]['login'];
How can I display all login-names?
Any help would be much appreciated.
Thanks in advance!
array_map is a universal function for tasks like this, in your case, this code would work:
$array = [['login' => "name23", 'id' => 12356], ['login' => "name12", 'id' => 12345], ['login' => "name34", 'id' => 12367]];
print_r(array_map(function($data) { return $data['login']; }, $array));
Manual: https://www.php.net/array-map
But for your specific task, array_column is simpler, as recommended by Aghilan B.
There is also array_walk function that can be used like this:
$array = [['login' => "name23", 'id' => 12356], ['login' => "name12", 'id' => 12345], ['login' => "name34", 'id' => 12367]];
array_walk($array, function($data) { print $data['login'] . "\n"; });
That can be useful if you want to do more with the logins than just printing it, it would not need to iterate twice.
You can use array_column() Function
$array = [['login' => "name23", 'id' => 12356], ['login' => "name12", 'id' => 12345], ['login' => "name34", 'id' => 12367]];
$login_array = array_column($array, 'login');
print_r($login_array);
Output
Array
(
[0] => "name23"
[1] => "name12"
[2] => "name34"
)
Use implode(', ', $login_array); to print as a string with commas
Related
I want to get separate field in array, I have array and some fields but I need single fields how can get below I given my code and out put of data(print_r) please how can I do this one, I'm new in php.
I want only for 'code' field only how can I get...
print_r() I'm getting this output:
Array ( [0] => Array ( [id] => 1 [code] => kg1 [name] => Kindergarden [status] => 1 [craeteddate] => 2022-02-03 17:33:05 )
My php code:
$data['classes'] = $this->enquiryform_model->get_class();
$class_code = $data['classes']['code'];
you have two arrays. 1 inside another. So to get the code you need to do this.
<?php
$data['classes'] = array( 0 => array( 'id' => 1, 'code' => 'kg1', 'name' => 'Kindergarden', 'status' => 1, 'craeteddate' => '2022-02-03 17:33:05' ));
$class_code = $data['classes'][0]['code'];
echo $class_code;
echo "\n";
$class_code = $data['classes'][0];
echo $class_code['code'];
?>
Here is the working example
Dunno if it is the right title or not, but i'm struggling to do the following thing:
say I have this array
Array
(
[0] => Array
(
[id_ptp] => 1
[denumire_ptp] => Hrană uscată
)
[1] => Array
(
[id_ptp] => 2
[denumire_ptp] => Hrană umedă
)
[2] => Array
(
[id_ptp] => 3
[denumire_ptp] => Hrană vie
)
)
how can I make it to become like this:
[
'1' => 'Hrană uscată',
'2' => 'Hrană umedă',
'3' => 'Hrană vie',
]
Better question, is there a function that does that? Because I was not able to find it.
array_column it is. Here is the one liner.
$result = array_column($your_array, 'denumire_ptp', 'id_ptp');
result : https://3v4l.org/qU0EU
I am retrieving data from the database with the help of belong to association using find method in cakephp. It's work perfectly but getting output like Array
(
[0] => Array
(
[PaymentLine] => Array
(
[Amount] => -1000.000
[OpenAmount] => -1000.000
[Narration] =>
)
[Payment] => Array
(
[TXNName] => Receipt-1
[TXNDate] => 2014-08-06
)
)
)
But I have to arrange data like Array
(
[0] => Array
(
[Amount] => -1000.000
[OpenAmount] => -1000.000
[Narration] =>
[TXNName] => Receipt-1
[TXNDate] => 2014-08-06
)
)
For these purpose I used Set::ClassicExtract method but that method not working for me... please help me...
Are you able to simply loop over the collection that is returned by the find method?
Perhaps try doing something like this:
$values = [];
foreach($array_of_arrays as $key => $array)
{
foreach($array as $value)
{
$values[] = $value;
}
}
$values will then contain all the values. The end result that you listed is not really possible to achieve if I understand what you are trying to do. This is because in that example you have duplicate keys for things such as 'id' and 'created'. If you only want to get the Arrays and store them in an array without the key then all you have to do is use:
array_values($array_of_arrays);
which will return the array but with the inner arrays having numeric keys instead of the enum ones.
If (for example) you had stored your data that you are getting back in a array called $dummy_data it would look something like this:
$dummy_data = [
'Profile' => Array
(
'id' => "12",
'user_id' => "121",
'skill' => "Baking Cakes",
'created' => "2007-05-01 10:31:01"
),
'User' => Array
(
'id' => "121",
'name' => "Gwoo the Kungwoo",
'created' => "2007-05-01 10:31:01"
)
];
If you know for a fact that the created values will always be the same for the 'Profile' and 'User' arrays then you can get a final array by using
array_merge($dummy_data['User'], $dummy_data['Profile']);
Is there a way to format the $this->find('all') array into the $this->find('list') in the view? The reason I ask is so that I can pass that new array into the form helper options and then use the $this->find('all') array to build some additional things I need?
Array (
[0] => Array ( [School] => Array ( [id] => 0 [name] => Nature [address] => 112 Main [max_students] => 25 [application_level] => 5 ) )
[1] => Array ( [School] => Array ( [id] => 1 [name] => Math [address] => 112 Smith [max_students] => 25 [application_level] => 0 ) )
[2] => Array ( [School] => Array ( [id] => 2 [name] => Art [address] => 112 Lane [max_students] => 25 [application_level] => 0 ) )
)
So this is the array I get when I do a find('all'). I want to build the array so it looks like:
Array (
[0] => 'Nature'
[1] => 'Math'
[2] => 'Art'
)
This is usually done by the $this->find('list') function. Though the reason I want the whole array is because I need to add the application_level into $this->Form->input() function. This is because I need to add the option of class with the application level attached so I show only the shows with the application level based on the previous selection.
EDIT: Can't I just do $this->find('list', [insert parameters here?]);? I just don't understand how you set up the additional parameters?
If your query isn't overly complicated and isn't going to return a excessive number of results, just run it twice (once for find all and once for find list).
Find all, list, first, whatever are all the same in terms of the paramaters you pass in. E.g.:
$this->Model->find('all', array(
'conditions' => array(
'field' => 500,
'status' => 'Confirmed'
),
'order' => 'id ASC'
));
... you literally replace all with list. In your case, probably easiest to do it twice, once for each. Like this:
$parameters = array(
'conditions' => array(
'field' => 500,
'status' => 'Confirmed'
),
'order' => 'id ASC'
);
$alldata = $this->Model->find('all', $parameters);
$listdata = $this->Model->find('list', $parameters);
Otherwise, you can loop through it and populate your own list:
$list = array();
foreach($findall as $row) {
$id = $row['id'];
$name = $row['name'];
$list[$id] = $name;
}
$this->set('listdata', $list);
Short answer to your question is that there's no quick, easy way to select all and list from the same query, but you can re use your parameters (conditions, order etc) by passing them in as predefined arrays, or populate your own list.
An alternative answer to creating the results formatted like find('list') from results from find('all') using CakePHP's hash utility:
//where $data is the result of find all
App::uses('Hash', 'Utility');
$ids = Hash::format($data, array('{n}.Model.id'), '{0}'); //ids in an array.
$names = Hash::format($data, array('{n}.Model.name'), '{0}'); //names in an array
$dataAsList = array_combine($ids, $names);
To improve on kai's answer. The Hash class has a method called combine that can do what you're trying to do in only one line
$list = Hash::combine($data,'{n}.Model.id','{n}.Model.name');
the $list will be a flat array like data from find('list');
Hey folks, please lend a hand to a PHP beginner. I'm trying to put a load of dynamically created variabled into an array to re-read later, reason is a SOAP message sent is a mess and im trying to create a less complicated array:
$placea = "place a";
$placeb = "place b";
$myarray = array();
echo "<pre>";
print_r($myarray);
echo "</pre>";
what i want to be able to do:
Array
(
[0] => [Place A] => Array
(
[0] => [Accommodation] => Array
(
[RoomId] => 001
[RoomAvail] => true
[Date] => 12.04.2011
)
[1] => [Accommodation] => Array
(
[RoomId] => 002
[RoomAvail] => true
[Date] => 12.04.2011
)
) Array
(
[1] => [Place B] => Array
(
[0] => [Accommodation] => Array
(
[RoomId] => 101
[RoomAvail] => true
[Date] => 12.04.2011
)
[1] => [Accommodation] => Array
(
[RoomId] => 102
[RoomAvail] => true
[Date] => 12.04.2011
)
)
)
how would i write that out in php? sorry if its bleek and/or the array structure is incorrect
So you just need to use the array initializer repetitively.
If you want to initialize an array in PHP with some values, say 1 through 4, you make a call like:
$foo = array(1, 2, 3, 4);
And if you want to make an associative array, where you store some key/value pairs, you make a call like:
$foo = array('key' => 'value', 'other key' => 'other value');
But you can of course nest calls, and mix and match layers of associative and non associative arrays to achieve something like your example, e.g.:
$foo = array(
'Place A' => array(
// note use of first array on the next line is
// to generate structure like [0] => 'Accomodation' => ...
array('Accomodation' => array(
'RoomId' => '001',
'RoomAvail' => true,
'Date' => '12.04.2011')
)),
array('Accomodation' => array(
'RoomId' => '002',
'RoomAvail' => true,
'Date' => '12.04.2011')
))
),
'Place B' => array(
array('Accomodation' => array(
'RoomId' => '101',
'RoomAvail' => true,
'Date' => '12.04.2011')
)),
array('Accomodation' => array(
'RoomId' => '102',
'RoomAvail' => true,
'Date' => '12.04.2011')
))
)
);
This will very nearly produce what you're looking for, to make it replicate exactly what you have you would wrap each 'Place A' with an array and each "place" would get its own assignment to some variable $foo (I assumed this wasn't actually what you wanted and wrote something maybe slightly more intuitive).
If you want to have a 'less complicated' array, you have a two arrays, one fore place a and one for place b and then merge them using array_merger() http://www.php.net/manual/en/function.array-merge.php.
Study up on the array functions control structures in the manual. Many different ways of achieving bloated arrays uglying up your code.
This would dynamically create an array.
foreach($soapResponse as $key1 => $value1){
foreach($value as $key2 => $value2){
// $key1 = Place A or B
// value1 = array of values
$arrayResponse[$key1][$key2] = $value2;
}
}