create new array from a multidimensional array - php

I have this multidimensional array:
Array (
[0] => Array (
[id] => 1
[list_name] => List_Red
)
[1] => Array (
[id] => 2
[list_name] => List_Blue
)
)
...and i would like to create a new array containing only the [id]'s from it.
I would appreciate it alot if you guys could help me with that ^^
Thanks in advance.

#fabrik Your solution indeed does work but it is also incorrect as PHP will throw a E_WARNING telling you that you're appending to an array that did not yet exist. Always initialise your variables before you use them.
$newList = array();
foreach($myList as $listItem) {
$newList[$listItem['id']] = $listItem['list_name'];
}
This is now a list of all your list_names in the following format.
Array (
1 => List_Red
2 => List_Blue
)
Much easier for you to work with and you can now iterate over it like so..
foreach($newList as $itemID => $itemName) {
echo "Item ID: $itemID - Item Name: $itemName<br>";
}

You could use array_map like this:
$new_array = array_map( function( $a ) { return $a['id']; }, $orig_array );
That's assuming PHP 5.3, for PHP < 5.3 you have to use create_function:
$new_array = array_map( create_function( '$a', 'return $a["id"];' ), $orig_array );

foreach($array as $label => $data)
{
$final[] = $data['id'];
}

Related

Array unique values PHP

I want to find the Unique values by username:
so the resulting array would be [0] =>JakeP, [1]=>TomC
My code currently works, but I was wondering is there a better way to accomplish this task with less loops, or using array_unique function?
Array
(
[0] => Array
(
[ID] => 3
[Username] => TomC
[Project_Name] => Inventory
)
[1] => Array
(
[ID] => 4
[Username] => JakeP
[Project_Name] => Inventory
)
[2] => Array
(
[ID] => 2
[Username] => TomC
[Project_Name] => Stocks
)
[3] => Array
(
[ID] => 1
[Username] => Tomc
[Project_Name] => Stocks
)
)
My code which works is :
$names_filter = array();
foreach($latest_projects as $project)
{
if(empty($names_filter))
{
$names_filter[] = $project['Username'];
}
else {
foreach($names_filter as $key=>$value)
{
if($value == $project['Username'])
{ break; }
else
{
$names_filter[] = $project['Username'];
}
}
}
}
If you're using PHP >= 5.5 you can take advantage of the array_column() function:
$uniqueNames = array_unique(
array_column($myArray, 'Username')
);
Prior to PHP 5.5, you can use:
$uniqueNames = array_unique(
array_map(
function($value) {
return $value['Username'];
},
$myArray
)
);
You can use the in_array function to simplify your code. Example:
$names_filter = array();
foreach($latest_projects as $project)
{
if(!in_array($project['Username'], $names_filter))
{
$names_filter[] = $project['Username'];
}
}
The in_array() function checks for the existence of a value in an array. So the foreach loop will only add a project username to the $names_filter array if it's not in the array. The output should be a list of unique usernames in the $names_filter array.
We can loop through $latest_projects and store each user name to new array ($filter). Since array can't have two elements with same keys, if the key exists it will be overwritten.
$filter = array();
foreach ($latest_projects as $project)
{
$filter[$project['Username']] = 1;
}
$filter = array_keys($filter);
I can't speak to the performance of this over other solutions, but a similar effect can be achieved with the use of array_map and array_unique. It's not as readable either though, which is just as important.
$uniqueUsers = array_unique(array_map(function ($p) { return $p['Username']; }, $latest_projects));

Returning Php multidimensional array in WordPress

I have the following array stored in the wordpress options table and I need to get the value of each title
a:1:{s:14:"swd_line_items";a:3:{i:0;a:1:{s:5:"title";s:9:"asdfasdfa";}i:1;a:1:{s:5:"title";s:13:"asdf asdf ada";}i:2;a:1:{s:5:"title";s:29:"fffffffffffffffffffffffffffff";}}}
I've tried nested foreach loops but nothing I do seems to work. There must be a simple solution?
function swd_get_line_items() {
$line_items = get_option('line_items_array');
$items = array();
foreach( $line_items as $item => $value ) {
foreach ($value as $new => $v) {
$items[] = array(
$new => $v
);
}
}
return $line_items;
}
Hope this helps :)
$array = unserialize('a:1:{s:14:"swd_line_items";a:3:{i:0;a:1:{s:5:"title";s:9:"asdfasdfa";}i:1;a:1:{s:5:"title";s:13:"asdf asdf ada";}i:2;a:1:{s:5:"title";s:29:"fffffffffffffffffffffffffffff";}}}');
foreach($array['swd_line_items'] as $item) {
echo $item['title'];
}
get_option() perfectly unsezrializes an array so there is no need to do it as the two other answers suggested it.
Then what you have is a two dimensional array but you are perfectly browsing it with two nested foreach.
By the way here is the final output of your code:
As you can see you perfectly extracted the titles:
Array
(
[0] => Array
(
[0] => Array
(
[title] => asdfasdfa
)
)
[1] => Array
(
[1] => Array
(
[title] => asdf asdf ada
)
)
[2] => Array
(
[2] => Array
(
[title] => fffffffffffffffffffffffffffff
)
)
)
But the issue here is that you do not return this array but you return this one:
return $line_items;
Change it into
return $items;
you mean this ?
function swd_get_line_items($serialized_array)
{
$line_items = unserialize($serialized_array);
$items = array();
foreach ($line_items['swd_line_items'] as $key => $item)
{
$items[$key] = $item['title'];
}
return $items;
}

Converting multidimensional array's values into a key value pair in a one-dimensional array while taking out a prefix out of one of the values?

I have an array in the following format:
Array (
[0] => Array
(
[option_id] => 10820
[option_name] => PREFIX_FIRST_OPT_KEY
[option_value] => FIRST_OPT_VALUE
[autoload] => yes
)
[1] => Array
(
[option_id] => 10821
[option_name] => PREFIX_SECOND_OPT_KEY
[option_value] => SECOND_OPT_VALUE
[autoload] => yes
)
[2] => Array
(
[option_id] => 10824
[option_name] => PREFIX_THIRD_OPT_KEY
[option_value] => SECOND_OPT_VALUE
[autoload] => yes
)
)
What is the appropriate function to use to get a one dimensional associative array with the following structure?
Array (
[FIRST_OPT_KEY] => FIRST_OPT_VALUE
[SECOND_OPT_KEY] => SECOND_OPT_VALUE
[THIRD_OPT_KEY] => THIRD_OPT_VALUE
)
I only want to keep the indicated values as key value pairs in the new array and ignore the rest - PREFIX_ is fixed length.
What I am doing right now:
foreach ( $the_original_array as $key => $value ) {
$new_key = substr($the_original_array[$key]['option_name'], 7);
$option_value = $the_original_array[$key]['option_value'];
$new_array[$new_key] = $option_value;
}
but I feel there ought to be a cleaner/more efficient way of accomplishing this
If you have PHP >= 5.5:
To extract values:
$result = array_column($array, 'option_value', 'option_name');
Then to remove prefix:
$result = array_combine(
array_map(
function($k){
return str_replace('PREFIX_', '', $k);
},
array_keys($result)
), $result
);
A way of simulating array_column() if you aren't running PHP 5.5+
$newArray = array_combine(
array_map(
function($value) {
return substr($value['option_name'], 7);
},
$the_original_array
),
array_map(
function($value) {
return $value['option_value'];
},
$the_original_array
)
);
The accepted answer is valid, but it causes the data to be iterated over multiple times. Assuming PHP < 5.5.0, using array_reduce will loop over the data only once, and return the same result:
$iterator = function($result, $record) {
$key = substr($record['option_name'], 7);
$result[$key] = $record['option_value'];
return $result;
};
$newArray = array_reduce($original, $iterator, array());
I would use array_column but for PHP < 5.5.0 what you have is about the best you can do, but you can use the $value that is generated by the foreach:
foreach ( $the_original_array as $value ) {
$new_key = substr($value['option_name'], 7);
$option_value = $value['option_value'];
$new_array[$new_key] = $option_value;
}
I think than foreach is good like:
$new = array();
foreach ($original_array as $item) {
$index = str_replace('PREFIX_', '', $item['option_name']);
$new[$index] = $item['option_value'];
}

Reproducing the new array from existing array(multi array)

Reproducing the new array from existing array(multi array)
If I have an array called as parameter:
$arr = Array
(
[0] => Array(0,Array(0=>'abc'))
[1] => Array(0,Array(1=>'def'))
[2] => Array(1,Array(0=>'ghi'))
)
Want to to a function that pass $arr some thing like this
function TODO($arr){
//
return $new_array;
}
And the function will return
RESULT WILL BE Reproduce elements from previous array ,And it will be got the result(returned):
Array
(
[0] => Array
(
[0] => 'abc'
[1] => 'def'
)
[1] => Array
(
[0] => 'ghi'
)
)
Anybody know how to do this?Please
thanks
I'm not 100% sure I've understood what you want, but if I have, this should work:
<?php
$arr = Array(
0 => Array(0, Array(0=>'abc')),
1 => Array(0, Array(1=>'def')),
2 => Array(1, Array(0=>'ghi'))
);
function transformArray($array) {
$newArray = array();
foreach ($array as $value) {
if (!isset($newArray[$value[0]])) {
$newArray[$value[0]] = array();
}
$newArray[$value[0]][] = array_pop($value[1]);
}
return $newArray;
}
$outputArray = transformArray($arr);
echo '<pre>' . print_r($outputArray, true) . '</pre>';
?>
I don't think so. If you have controll over how these text arrays are turned into text, you should use serialize() and unserialize(). The fastest and easiest way.
If you still need to create arrays from the strings you have provided, you will probably have to construct quite a complex function to do that.

weird php array

my php array looks like this:
Array (
[0] => dummy
[1] => stdClass Object (
[aid] => 1
[atitle] => Ameya R. Kadam )
[2] => stdClass Object (
[aid] => 2
[atitle] => Amritpal Singh )
[3] => stdClass Object (
[aid] => 3
[atitle] => Anwar Syed )
[4] => stdClass Object (
[aid] => 4
[atitle] => Aratrika )
) )
now i want to echo the values inside [atitle].
to be specific i want to implode values of atitle into another variable.
how can i make it happen?
With PHP 5.3:
$result = array_map(function($element) { return $element->atitle; }, $array);
if you don't have 5.3 you have to make the anonymous function a regular one and provide the name as string.
Above I missed the part about the empty element, using this approach this could be solved using array_filter:
$array = array_filter($array, function($element) { return is_object($element); });
$result = array_map(function($element) { return $element->atitle; }, $array);
If you are crazy you could write this in one line ...
Your array is declared a bit like this :
(Well, you're probably, in your real case, getting your data from a database or something like that -- but this should be ok, here, to test)
$arr = array(
'dummy',
(object)array('aid' => 1, 'atitle' => 'Ameya R. Kadam'),
(object)array('aid' => 2, 'atitle' => 'Amritpal Singh'),
(object)array('aid' => 3, 'atitle' => 'Anwar Syed'),
(object)array('aid' => 4, 'atitle' => 'Aratrika'),
);
Which means you can extract all the titles to an array, looping over your initial array (excluding the first element, and using the atitle property of each object) :
$titles = array();
$num = count($arr);
for ($i=1 ; $i<$num ; $i++) {
$titles[] = $arr[$i]->atitle;
}
var_dump($titles);
This will get you an array like this one :
array
0 => string 'Ameya R. Kadam' (length=14)
1 => string 'Amritpal Singh' (length=14)
2 => string 'Anwar Syed' (length=10)
3 => string 'Aratrika' (length=8)
And you can now implode all this to a string :
echo implode(', ', $titles);
And you'll get :
Ameya R. Kadam, Amritpal Singh, Anwar Syed, Aratrika
foreach($array as $item){
if(is_object($item) && isset($item->atitle)){
echo $item->atitle;
}
}
to get them into an Array you'd just need to do:
$resultArray = array();
foreach($array as $item){
if(is_object($item) && isset($item->atitle)){
$resultArray[] = $item->atitle;
}
}
Then resultArray is an array of all the atitles
Then you can output as you'd wish
$output = implode(', ', $resultArray);
What you have there is an object.
You can access [atitle] via
$array[1]->atitle;
If you want to check for the existence of title before output, you could use:
// generates the title string from all found titles
$str = '';
foreach ($array AS $k => $v) {
if (isset($v->title)) {
$str .= $v->title;
}
}
echo $str;
If you wanted these in an array it's just a quick switch of storage methods:
// generates the title string from all found titles
$arr = array();
foreach ($array AS $k => $v) {
if (isset($v->title)) {
$arr[] = $v->title;
}
}
echo implode(', ', $arr);
stdClass requires you to use the pointer notation -> for referencing whereas arrays require you to reference them by index, i.e. [4]. You can reference these like:
$array[0]
$array[1]->aid
$array[1]->atitle
$array[2]->aid
$array[2]->atitle
// etc, etc.
$yourArray = array(); //array from above
$atitleArray = array();
foreach($yourArray as $obj){
if(is_object($obj)){
$atitleArray[] = $obj->aTitle;
}
}
seeing as how not every element of your array is an object, you'll need to check for that.

Categories