Get column content as array key [duplicate] - php

This question already has answers here:
Generate an associative array from an array of rows using one column as keys and another column as values
(3 answers)
Closed 7 months ago.
I am rewrting a newsletter-thingy.
I have a table for all newsletter fields, that is like this:
field_uid | field_name | field_content | field_letter_id
Where f.x. the column field_name can have the value letter_headline
and the column field_content can have the value My headline.
When I do this:
$fields = $this->db->dbh->query("SELECT field_name, field_content FROM newsletter_fields WHERE field_letter_uid = '". $letter_id ."'");
foreach($fields->fetchAll(PDO::FETCH_ASSOC) as $key) {
print_r($key);
}
It will correctly give me this:
Array ( [field_name] => letter_image0 [field_content] => image.jpg )
Array ( [field_name] => letter_headline [field_content] => My headline )
Array ( [field_name] => letter_headline_size [field_content] => 12 )
Array ( [field_name] => letter_sub_headline [field_content] => My subheadline )
Array ( [field_name] => letter_sub_headline_size [field_content] => 10 )
Array ( [field_name] => letter_content [field_content] => Letter content )
Array ( [field_name] => letter_link [field_content] => www.example.com )
Array ( [field_name] => letter_link_txt [field_content] => Example )
What I want is to build an array like this
$field["letter_image"] = "image.jpg";
$field["letter_headline"] = "My headline"
And then I can output the content with:
echo $field["letter_image"];
But I can't seem to figure out how to set the field array.

$result = array_combine(array_column($data, 'field_name'), $data);

This is an old question, but I think it is worth mentioning that [array_column][1] function can accept the name of the column to use as array keys as a third parameter, so the easiest solution for this is :
// field_content column will be used as values of the array
// field_name column will be used as keys
$result = array_column($data, 'field_content', 'field_name');
Applying this to the example of #Toskan's answer:
$x = [['id' => 5, 'name' => 'john'], ['id' => 15, 'name' => 'jim']];
$result = array_column($x, 'name', 'id');
print_r($result);
// outputs Array ( [5] => john [15] => jim )

Easiest solution is just iterate through your array, like:
$result = [];
foreach($data as $row)
{
$result[$row['field_name']] = $row['field_content'];
}
You'll probably want to do this in your fetch cycle (so you'll avoid then iterating through rows twice)

well, almas solution is not using the native implementation that is optimized.
I am not saying it is wrong, just not optimized.
This should be optimized:
$x = [['id' => 5, 'name' => 'john'], ['id' => 15, 'name' => 'jim']];
$keys = array_column($x, 'id');
$values = array_column($x, 'name');
$result = array_combine($keys, $values);
var_dump($result);
//outputs array(2) { [5]=> string(4) "john" [15]=> string(3) "jim" }
This does not work with PHP 4 and only works php > 5.5

Use the third parameter of array_column
$rows = [
[
'field_name' => 'letter_image',
'field_content' => 'image.jpg'
],
[
'field_name' => 'letter_headline',
'field_content' => 'My headline'
],
];
$fields = array_column($rows, 'field_content', 'field_name');
---
php > var_dump($fields);
array(2) {
["letter_image"]=> string(9) "image.jpg"
["letter_headline"]=> string(11) "My headline"
}
https://www.php.net/manual/es/function.array-column.php

Garh... Nevermind..
Fairly simple
$field[$key["field_name"]] = $key["field_content"];

Related

search some object data in array [duplicate]

This question already has answers here:
Filter multidimensional array by value in array [duplicate]
(2 answers)
Closed 3 years ago.
I have an array like this:
$array = (
[0] => stdClass Object
(
[ID] => 420
[name] => Mary
)
[1] => stdClass Object
(
[ID] => 10957
[name] => Blah
)
)
...
I found some solution to search using loop like this:
$item = null;
foreach($array as $struct) {
if ($v == $struct->ID) {
$item = $struct;
break;
}
}
Because of the large amount of data, I want to change it so that I can retrieve multiple values ​​instead of one value at a time (ex: $array->420 = Mary, $array->10957 = Blah,...). Which way would be the most optimal in this case?
If you index your main array by the ID (use array_column() for this), and an array of the ID's you are after, then array_intersect_key() will extract all of the ones you want into a list of the matches...
$array =[
(Object)
[
"ID" => 420,
"name" => "Mary"
],
(Object)
[
"ID" => 10957,
"name" => "Blah"
]
];
$ids = [420, 10957];
$indexArray = array_column($array, null, "ID" );
$matches = array_intersect_key($indexArray, array_flip($ids));
print_r($matches);
gives..
(
[420] => stdClass Object
(
[ID] => 420
[name] => Mary
)
[10957] => stdClass Object
(
[ID] => 10957
[name] => Blah
)
)
You need to use array_flip() on the ID's array to convert the value into the key to work with the array_intersect_key() function.
You can then use array_values() if you don't want the key for this data (i.e. the ID)
Here's three possible solutions depending on your needs, using array_column:
Build an ID => name array:
$result = array_column($array, 'name', 'ID');
Build an ID => entry array (if you have more stuff than just the name):
$result = array_column($items, null, 'ID');
Alternative using array_reduce:
$result = array_reduce($array, static function ($result, $item) {
$result[$item['ID']] = $item;
return $result;
});
Demo: https://3v4l.org/fLMgL

Convert a multidimensional array (php) [duplicate]

This question already has answers here:
Generate an associative array from an array of rows using one column as keys and another column as values
(3 answers)
Closed 3 years ago.
im currently struggling with converting this array in PHP to a more simplified one. This is my array to start with stored in $array:
[0] => Array
(
[name] => name-1
[value] => xXX
)
[1] => Array
(
[name] => name-2
[value] => YYY
)
I would like to transfrom this array to this simplified one $array_new:
[0] => Array
(
[name-1] => xXX
)
[1] => Array
(
[name-2] => YYY
)
I sadly don't know were to start... Could somebody help me out?
Edit: After I converted the array via array_column() oder foreach loop I still cant get the right data with $array_new['name-2'];
You can use array-column to do that. The documentation said:
array_column ( array $input , mixed $column_key [, mixed $index_key = NULL ] ) : array
So do:
$first_names = array_column($array, 'value', 'name');
Live example: 3v4l
Question
Alright, this is a question I see a lot of beginners deal with.
Just be a little creative:
Answer
//Let's get your old array:
$old = [
0 => [
'name' => 'name-1',
'value' => 'xXX'
],
1 => [
'name' => 'name-2',
'value' => 'YYY'
]
];
//Let's create an array where we will store the new data:
$result = [];
foreach($old as $new) { //Loop through
$result[$new['name']] = $new['value']; //Store associatively with value as value
}
var_dump($result);
Result:
Array[2] => [
[name-1] => xXX,
[name-2] => YYY
];
Using a foreach:
<?php
$items =
[
[
'plant' => 'fern',
'colour' => 'green'
],
[
'plant' => 'juniper',
'colour' => 'blue'
]
];
foreach($items as $item) {
$output[][$item['plant']]=$item['colour'];
}
var_dump($output);
Output:
array(2) {
[0]=>
array(1) {
["fern"]=>
string(5) "green"
}
[1]=>
array(1) {
["juniper"]=>
string(4) "blue"
}
}

PDO - array_map return objects ids in keys

hey i have array with returned keys
$temp = $sth->fetchAll(PDO::FETCH_ASSOC);
my result looks like this:
[0] => [
'id' = 11,
'title' => 't1'
]
[1] => [
'id' = 12,
'title' => 't2'
]
if i want to return ids as key i call something like this:
$temp = array_map(function($v){return $v[0];}, $sth->fetchAll(PDO::FETCH_GROUP|PDO::FETCH_ASSOC));
and my resoult looks like this:
[11] => [
'title' => 't1'
]
[12] => [
'title' => 't2'
]
how to return array of objects by ID? when i do this i dont have methods in object...
$temp = array_map(function($v){return $v[0];}, $sth->fetchAll(PDO::FETCH_GROUP|PDO::FETCH_CLASS));
I will do a bit easier code like below:-
$fianl_array = array_combine(array_column($temp,'id'),$temp);
Output:- https://eval.in/993728
Reference:-
array_column()
array_combine()
Using foreach:
foreach($input as $k=>$v){
$output[$v['id']] = array('title'=>$v['title']);
}
print_r($output);
Just had to add this as an answer as I believe it's the shortest way of doing this, using array_column() with a third parameter which is the key you want the data indexed by. If you use null as the second parameter, it will index all the data by 'id', you could instead use 'title' and this will only index the title columns by ID...
$output = array_column($temp,null,'id');
Which gives...
Array
(
[11] => Array
(
[id] => 11
[title] => t1
)
[12] => Array
(
[id] => 12
[title] => t2
)
)

Count the keys of multi-dimension array php

Maybe the title can not explain my question ,please see my example :
I have an multi-dimension array like this :
Array
(
[0] => Array
(
[name] => 'A'
[ec_dest_name] => 楽天testuser_998
),
[1] => Array
(
[name] => 'A'
[ec_dest_name] => 楽天testuser_998
),
[2] => Array
(
[name] => 'B'
[ec_dest_name] => 楽天testuser_998
),
[3] => Array
(
[name] => 'C'
[ec_dest_name] => 楽天testuser_998
)
)
I want to count the element by key name , it mean that I want to return an array like :
Array ('A' => 2 , 'B'=>1, 'C'=>1)
Any quick way to accomplish that , I could loop array and count but I think it is not a good idea
Thank in advanced
You can use array_count_values & array_column togather -
$counts = array_count_values(array_column($your_array, 'name'));
Output
array(3) {
["A"]=>
int(2)
["B"]=>
int(1)
["C"]=>
int(1)
}
Demo
As Mark Baker suggested for older PHP versions -
$counts = array_count_values(
array_map(function($value) {
return $value['name'];
}, $your_array)
);
You may as well do that with 2 Loops as shown below. You might test this also HERE.
<?php
$arrSections = array();
$arrCounts = array();
$arrMain = array(
array(
'name' => "A",
'ec_dest_name' => "楽天testuser_998",
),
array(
'name' => "A",
'ec_dest_name' => "楽天testuser_998",
),
array(
'name' => "B",
'ec_dest_name' => "楽天testuser_998",
),
array(
'name' => "C",
'ec_dest_name' => "楽天testuser_998",
),
);
// BUNDLE ARRAYS WITH SIMILAR name INTO ONE GROUP
// THUS CREATING A MULTI-DIMENSIONAL ARRAY WHOSE MAIN KEYS CORRESPOND TO
// THE name OF THE MEMBER ARRAYS IN THE GROUP.
foreach($arrMain as $iKey=>$subMain){
$name = $subMain['name'];
if(!array_key_exists($name, $arrSections)) {
$arrSections[$name] = array();
}
$arrSections[$name][] = $subMain;
}
// FETCH THE COUNTS OF EACH GROUP AND MAKE AN ARRAY OUT OF IT...
foreach($arrSections as $k=>$v){
$arrCounts[$k] = count($v);
}
var_dump($arrCounts);
//OUTPUTS::
array (size=3)
'A' => int 2
'B' => int 1
'C' => int 1

Creating Associative Array in PHP

I have a multidimensional array.
$shop = array(
array("appn1", "pub1" ,"pub2" , "pub3"),
array("appn2", "pub1"),
array("appn3", "pub1" ,"pub2")
);
The first item in each array is application number and the rest in each array are the publication numbers. I get the first item(application number) and the last item of each array(latest publication number) like this
$index = count(array_keys($shop));
for($i=0;$i<$index;$i++){
$appln_nr = $shop[$i][0];
echo $appln_nr;
$publn_nr_index = count(array_keys($shop[$i]))-1;
$publn_nr = $shop[$i][$publn_nr_index];
echo $publn_nr;
}
Now I have application number and publication number for each inner array.
I want to create an associative array from the application numbers and publication numbers.
where the key should be the application number and its value is the publication number.
Thanks
EDIT
What I am getting from $shop array
Array
(
[0] => Array
(
[0] => appn1
[1] => pub1
[2] => pub2
[3] => pub3
)
[1] => Array
(
[0] => appn2
[1] => pub1
)
[2] => Array
(
[0] => appn3
[1] => pub1
[2] => pub2
)
)
And this is what I need in my associative array
Array(
"appn1" => "pub3"
"appn2" => "pub1"
"appn3" => "pub2"
)
Finally i understood what you wanted, after your edit XD:
$shop = array(
array("appn1", "pub1" ,"pub2" , "pub3"),
array("appn2", "pub1"),
array("appn3", "pub1" ,"pub2")
);
$shopNew = array();
foreach($shop as $value){
$shopNew[$value[0]] = end($value);
}
// now if you want you can replace $shop and unset $shopNew
$shop = $shopNew;
unset($shopNew);
print_r($shop);
the output is this:
Array (
[appn1] => pub3
[appn2] => pub1
[appn3] => pub2
)
You can try
$shop = array(
array("appn1","pub1","pub2","pub3"),
array("appn2","pub1"),
array("appn3","pub1","pub2")
);
$final = array();
array_map(function ($var) use(&$final) {$final[reset($var)] = end($var);}, $shop);
var_dump($final);
Output
array
'appn1' => string 'pub3' (length=4)
'appn2' => string 'pub1' (length=4)
'appn3' => string 'pub2' (length=4)
You can easily convert your array into a new format by using the first element as key (see reset) and the last element (see end) as value:
foreach($shop as $fl) {
$v[reset($fl)] = end($fl);
}
Result is in $v then.
If you want to transform the array you need to delete each element as well:
foreach($shop as $v => $fl) {
$shop[reset($fl)] = end($fl);
unset($shop[$v]);
}
Result is in $shop then. Unset takes care of removing from the array.
Output in both cases is:
array(3) {
'appn1' =>
string(4) "pub3"
'appn2' =>
string(4) "pub1"
'appn3' =>
string(4) "pub2"
}
try this:
foreach($shop as $k => $v) {
$new_arr[$v[0]] = end($v);
}
It should give you this result,
$new_arr = array(
"appn1" => "pub3",
"appn2" => "pub1",
"appn3" => "pub2"-
);
You can also create like this,
$arrField = [];
$arrField['id'] = '0001';
$arrField["first_name"] ='Demo Test';
print_r($arrField);
print_r($arrField) display output like this.
Array ( [id] => 0001 [first_name] => Demo Test )

Categories