I have the following array:
Array
(
[0] => Array
(
[User] => Array
(
[firstname] => Chris
[lastname] => Willis
)
)
[1] => Array
(
[User] => Array
(
[firstname] => Test
[lastname] => Willis
)
)
...
I need it to be transformed into a structure similar to this:
Array
{
'Chris-Willis' => 0
'Test-Willis' => 1
....
What are some array functions to help to do this?
So it needs to be:
firstname-lastname => id
$grouped = array();
foreach ($users as $i => $user) {
$grouped["{$user['User']['firstname']}-{$user['User']['lastname']}"] = $i;
}
If the array is exactly as shown above, this should also do it:
$grouped = array_combine(array_map(function ($u) { return join('-', current($u)); }, $users), array_keys($users));
CakePHP has the Set::combine() method to help with such situations.
I'm assuming that you want the array values to be the database ID of the user, rather than the array index.
$users = $this->User->find('all', array(
'fields' => array('id', 'firstname', 'lastname'),
));
$usersMap = Set::combine(
$users,
array('%1$s-%2$s', '{n}.User.firstname', '{n}.User.lastname') // sprintf() formatting
'{n}.User.id',
);
foreach $original_array as $key=>$temp
{
$some_other_array[$temp['USER']['firstname']."-".$temp['USER']['lastname']] = $key;
}
The following code should do the trick
//$names is the name of your array
$namesId = array();
foreach ($names as $k=>$v)
{
$temp = $v["User"]["firstname"] . "-" . $v["User"]["lastname"];
$namesId[$temp] = $k;
}
Related
I have this array:
[docs] => Array
(
[indexone] => Array ( [0] => P008062518 )
[indextwo] => Array ( [0] => )
[indexthree] => Array ( [0] => 0000141334 )
[indexfour] => Array ( [0] => P006871638 )
[indexfive] => Array ( [0] => 0000910067 )
[indexsix] => Array ( [0] => )
)
I need to end with this one, extracting all values from the given key:
[docValues] => Array
(
[indexone] => Array ( P008062518, 0000141334, P006871638, 0000910067 )
)
I try this loop but i end with the same array structure :
foreach($values as $key => $data)
{
if(array_key_exists('docs', $data) )
{
$filtered = array_filter($data['docs'], function($var) { return !empty($var);});
$numDocs = array_values($filtered);
$values[$key]['docValues'] = $numDocs;
}
}
How can it be done ?
To get that exact array output:
$result['docValues'][key($values['docs'])] =
array_filter(array_column($values['docs'], 0));
Get the first key to use it as your new key with key()
Get an array of all values in the 0 indexes with array_column()
Remove empty elements using array_filter()
If your first array is called $docArray, then you can do the following:
$docValuesArray = array();//declaring the result array
$indexoneArray = array();//declaring the array you will add values
//to in the foreach loop
foreach ($docArray as $value)
{
$indexoneArray[] = $value[0];//giving each of the values
//found in $docArray to the $indexoneArray
}
$docValueArray[] = $indexoneArray;//adding the $indexoneArray
//to the $docsValueArray
Let me know if that worked for you.
This should do the trick for you:
$docs = [
'indexone' => ['P008062518'],
'indextwo' => [ ],
'indexthree' => ['0000141334'],
'indexfour' => ['P006871638'],
'indexfive' => ['0000910067'],
'indexsix' => [ ],
];
$allDocs = array();
foreach($docs as $key => $doc) {
$docString = implode("<br>",$doc);
if (empty($docString)) {
continue;
}
$allDocs[] = $docString;
}
$allDocsString = implode("<br>",$allDocs);
echo($allDocsString);
P0080625180000141334P0068716380000910067
Simply do this:
Your array
$arr = array("docs" =>
array(
'indexone' => array('P008062518'),
'indextwo' => array(''),
'indexthree' => array('0000141334'),
'indexfour' => array('P006871638'),
'indexfive' => array('0000910067'),
'indexsix' => array('')
)
);
Process:
echo '<pre>';
$index = key($arr["docs"]);
$output['docValues'][$index] = implode('<br/>', array_filter(array_column($arr['docs'], 0)));
print_r($output);
Explanation:
key = key function Returns the first index.
implode = collapse all the array items with the delimiter of <br/>
array_filter = filters the values of an array using a callback
function.
array_column = returns the values from a single column in the input
array.
Result:
Array
(
[docValues] => Array
(
[indexone] => P008062518<br/>0000141334<br/>P006871638<br/>0000910067
)
)
use array_filter() function . if you pass array in array_filter then remove all empty and NULL data record
I want to combine several arrays into one, they are the result of a form post with an unknown number of elements, eg:
$ids = [53,54,55];
$names = ['fire','water','earth'];
$temps = [500,10,5];
What i want is to make a function that takes these arrays as an input and produces a single output, like
$elements = [['id'=>53,'name'=>'fire','temp'=>500] , ['id'=>54,'name'=>'water','temp'=>500] , ['id'=>55,'name'=>'earth','temp'=>500]]
I came up with the following solution:
function atg($array) {
$result = array();
for ($i=0;$i<count(reset($array));$i++) {
$newAr = array();
foreach($array as $index => $val) {
$newAr[$index] = $array[$index][$i];
}
$result[]=$newAr;
}
return $result;
}
It can be called like
$elements = atg(['id' => $ids, 'name' => $names, 'temp' => $temps]);
And it produces the right output. To me it seems a bit overly complicated though, and I'm sure this is a common problem in PHP for form posts, combining seperate fields into a single array per item. What would be a better solution?
You can loop through all of your 3 arrays at once with array_map(). There you can just return the new array with a value of each of the 3 arrays, e.g.
$result = array_map(function($id, $name, $temp){
return ["id" => $id, "name" => $name, "temp" => $temp];
}, $ids, $names, $temps);
Use below code:-
$ids = [53,54,55];
$names = ['fire','water','earth'];
$temps = [500,10,5];
$result = [];
foreach($ids as $k=>$id){
$result[$k]['id'] = $id;
$result[$k]['name'] =$names[$k];
$result[$k]['temp'] = $temps[0];
}
echo '<pre>'; print_r($result);
output:-
Array
(
[0] => Array
(
[id] => 53
[name] => fire
[temp] => 500
)
[1] => Array
(
[id] => 54
[name] => water
[temp] => 500
)
[2] => Array
(
[id] => 55
[name] => earth
[temp] => 500
)
)
If you are ok with a destructive solution, array_shift could do the trick :
$elements = array();
while (!empty($ids)) {
$elements[] = array(
'id' => array_shift($ids),
'name' => array_shift($names),
'temp' => array_shift($temps),
);
}
If you want to make a function, using the same arguments than your example, a solution could be
function atg($array) {
$elements = array();
while (!empty($array[0])) {
$new_element = array();
foreach ($array as $key_name => $array_to_shift) {
$new_element[$key_name] = array_shit($array_to_shift);
}
$elements[] = $new_element;
}
return $elements;
}
$result[$ids]['name'] = $names[0];
$result[$ids]['temp'] = $temps[0]
I'm trying to store data in an array from a database.
After printing the array, I need something like this :
Array ( [ABBA] => ?search=ABBA [ACDC] => ?search=ACDC [Ace of Spades] => ?search=AceOfSpades)
But currently, I have this :
Array ( [url] => ?search=ABBA [title] => ABBA ) Array ( [idtitle] => ?search=ACDC [title] => ACDC ) Array ( [idtitle] => ?search=AceOfSpades [title] => Ace of Spades )
Here is my code to get the data and store into the array :
$key = $_POST['latestQuery'];
$requete = $bdd->prepare('SELECT url, title FROM articles WHERE title LIKE :key LIMIT 10');
$requete->execute(array('key' => '%'.$key.'%'));
$result_array[] = array();
foreach($requete->fetchAll(PDO::FETCH_ASSOC) as $search)
{
print_r($result_array[$search['title']] = $search);
}
And here this my table structure :
url | title
$search=ACDC | ACDC
Do you think there is a way to formate my array?
Remove print_r from a foreach:
$result_array = array();
foreach($requete->fetchAll(PDO::FETCH_ASSOC) as $search)
{
$result_array[$search['title']] = $search['url'];
}
print_r($result_array);
You can try this:
// testing array
$yourArray = array(
array(
'url'=>'?search=ABBA',
'title'=>'ABBA',
),
array(
'url'=>'?search=BABA',
'title'=>'BABA',
),
array(
'url'=>'?search=CBAA',
'title'=>'CBAA',
),
);
// solution
$myArr = array();
foreach ($yourArray as $key => $value) {
$myArr[$value['title']] = $value['url'];
}
echo "<pre>";
print_r($myArr);
Result is:
Array
(
[ABBA] => ?search=ABBA
[BABA] => ?search=BABA
[CBAA] => ?search=CBAA
)
I am having a terrible time getting this to work I have been struggling with it for a couple hours now. Can someone please help me? I have included a fiddle.
I believe my problem is in this string:
$$salesAndOwner[$i]["$salesAndOwner[$i]".$l] = $salesAndOwner[$i.$l][$param] = $values[$l];
Basically I have the following multidimensional array:
[sales] => Array
(
[FirstName] => Array
(
[0] => salesFirst1
[1] => salesFirst2
)
[LastName] => Array
(
[0] => salesLast1
[1] => salesLast2
)
)
[decisionmaker] => Array
(
[FirstName] => Array
(
[0] => dmFirst1
[1] => dmFirst2
)
[LastName] => Array
(
[0] => dmLast1
[1] => dmLast2
)
)
)
I need this to be reorganized like I did with the following array:
Array
(
[additionallocations0] => Array
(
[Address] => Address1
[State] => State1
)
[additionallocations1] => Array
(
[Address] => Address2
[State] => State2
)
)
Here is the original:
Array
(
[additionallocations] => Array
(
[Address] => Array
(
[0] => Address1
[1] => Address2
)
[State] => Array
(
[0] => State1
[1] => State2
)
)
This is how I reorganize the above array:
if(isset($_POST['additionallocations'])) {
$qty = count($_POST['additionallocations']["Address"]);
for ($l=0; $l<$qty; $l++)
{
foreach($_POST['additionallocations'] as $param => $values)
{
$additional['additionallocations'.$l][$param] = $values[$l];
}
}
And this is what I am using for the sales and decisionmaker array. If you notice I have an array that contains sales and decisionmaker in it. I would like to be able to sort any future arrays by just adding its primary arrays name. I feel I am close to solving my problem but I can not get it to produce right.
$salesAndOwner = array(0 => "sales", 1 => "decisionmaker");
for($i = 0; $i < 2; $i++){
$qty = count($_POST[$salesAndOwner[$i]]["FirstName"]);
for ($l=0; $l<$qty; $l++)
{
foreach($_POST[$salesAndOwner[$i]] as $param => $values)
{
$$salesAndOwner[$i]["$salesAndOwner[$i]".$l] = $salesAndOwner[$i.$l][$param] = $values[$l];
}
}
}
In the above code I hard coded 'sales' into the variable I need it to make a variable name dynamically that contains the sales0 decisionmaker0 and sales1 decisionmaker1 arrays so $sales and $decisionmaker
I hope this makes sense please let me know if you need any more info
Let's break it down. Using friendly variable names and spacing will make your code a lot easier to read.
Remember. The syntax is for you to read and understand easily. (Not even just you, but maybe future developers after you!)
So you have an array of groups. Each group contains an array of attributes. Each attribute row contains a number of attribute values.
PHP's foreach is a fantastic way to iterate through this, because you will need to iterate through (and use) the index names of the arrays:
<?php
$new_array = array();
// For each group:
foreach($original_array as $group_name => $group) {
// $group_name = e.g 'sales'
// For each attribute in this group:
foreach($group as $attribute_name => $attributes) {
// $attribute_name = e.g. 'FirstName'
// For each attribute value in this attribute set.
foreach($attributes as $row_number => $attribute) {
// E.g. sales0
$row_key = $group_name . $row_number;
// if this is the first iteration, we need to declare the array.
if(!isset($new_array[$row_key])) {
$new_array[$row_key] = array();
}
// e.g. Array[sales0][FirstName]
$new_array[$row_key][$attribute_name] = $attribute;
}
}
}
?>
With this said, this sort of conversion may cause unexpected results without sufficient validation.
Make sure the input array is valid (e.g. each attribute group has the same number of rows per group) and you should be okay.
$salesAndOwner = array("sales", "decisionmaker");
$result = array();
foreach ($salesAndOwner as $key) {
$group = $_POST[$key];
$subkeys = array_keys($group);
$first_key = $subkeys[0];
foreach ($group[$first_key] as $i => $val) {
$prefix = $key . $i;
foreach ($subkeys as $subkey) {
if (!isset($result[$prefix])) {
$result[$prefix] = array();
}
$result[$prefix][$subkey] = $val;
}
}
}
DEMO
Try
$result =array();
foreach($arr as $key=>$val){
foreach($val as $key1=>$val1){
foreach($val1 as $key2=>$val2){
$result[$key.$key2][$key1] = $val2;
}
}
}
See demo here
I have the following $qtips_messages array,
Array
(
[0] => Array
(
[id] => 1
[tips_title] => email_tips
[tips_message] => ex:xxxxx#xyz.com
[tips_key] => key_email
)
[1] => Array
(
[id] => 2
[tips_title] => website_tips
[tips_message] => ex:http://www.yahoo.co.in
[tips_key] => key_website
)
[2] => Array
(
[id] => 3
[tips_title] => zipcode_tips
[tips_message] => ex:60612
[tips_key] => key_zipcode
)
[3] => Array
(
[id] => 4
[tips_title] => phone_tips
[tips_message] => ex:1234567890
[tips_key] => key_phone
)
)
For example, I want to get the tips message for the tip_title 'email_tips'
I have tried with following code,
foreach($qtips_messages as $qtipsArray){
foreach($qtipsArray as $qkey=>$qvalue){
if($qtipsArray['tips_title'] == 'email_tips'){
$emailtipsMessage = $qtipsArray['tips_message'];
}
}
}
When i ran the above code i did not get any value.
What is wrong with this code?
You only need one loop:
$message = null;
foreach ($array as $tips) {
if ($tips['tips_title'] == 'email_tips') {
$message = $tips['tips_message'];
break;
}
}
I'd probably go for something like this though:
$message = current(array_filter($array, function ($tip) { return $tip['tips_title'] == 'email_tips'; }));
echo $message['tips_message'];
$array = array();
foreach($result AS $k =>$val)
$array[$val['tips_key']] = $val['tips_message'];
return $array;
Now the array $array have all the values for q-tips based on their keys...
Hope this will helps you...
try this way.
$array = array();
foreach($qtips_messages AS $k =>$val):
if($val['tips_title']=='email_tips')
{
$array[$val['tips_key']] = $val['tips_message'];
print_r($array);
break;
}
endforeach;