This is an array of PHP database output:
[
[hi]=>array(
[text] => 'ok'
)
[work]=>array(
[text] => 'usa'
)
[city]=>array(
[text] => 'newyork'
)
]
How do I convert it to look like this:
[
[hi]=> 'ok'
[work]=> 'usa'
[city]=> 'newyork'
]
You just want to loop over the array and build your newly formatted array.
<?php
$arr = [
'please' => [
'text' => 'it'
],
'use' => [
'text' => 'will'
],
'google' => [
'text' => 'help'
]
];
$formattedArr = [];
foreach ($arr as $k => $v) {
$formattedArr[$k] = $v['text'];
}
Another way using some array sorting methods to get us a one liner:
$formattedArr = array_combine( array_keys($arr), array_column($arr, 'text'));
array_combine is a php function that creates a new array using an array for keys and an array for values.
Simply enough, array_keys gets - you guessed it - the keys of the array.
array_column creates an array of a selected property from an inner array, so in this case, it goes plucks the 'text' values from the inner arrays.
Related
In my Laravel project, I have a dot notation array which I need to convert to a multi-dimensional array.
The array is something like this:
$dotNotationArray = ['cart.item1.id' => 15421a4,
'cart.item1.price' => '145',
'cart.item2.id' => 14521a1,
'cart.item2.price' => '1245'];
How can I expand it to an array like:
'cart' => [
'item1' => [
'id' => '15421a4',
'price' => 145
],
'item2' => [
'id' => '14521a1',
'price' => 1245,
]
]
How can I do this?
In Laravel 6+ you can use Arr::set() for this:
The Arr::set method sets a value within a deeply nested array using "dot" notation:
use Illuminate\Support\Arr;
$multiDimensionalArray = [];
foreach ($dotNotationArray as $key => $value) {
Arr::set($multiDimensionalArray , $key, $value);
}
dump($multiDimensionalArray);
If you are using Laravel 5.x you can use the array_set() instead, which is functionally identical.
Explanation:
Arr::set() sets value for a key in dot notation format to a specified key and outputs an array like ['products' => ['desk' => ['price' => 200]]]. so you can loop over your array keys to get a multidimensional array.
How to get column from a multidimensional with nested key
I have an array which is multidimensional. I have to pull a key as column but it is nested. like object accessing how to achieve this with minimum line of code or optimized.
Array
$array = [
[
'price' => [
'cost' => 200, 'tax' => 10, 'total' => 210
],
'otherKey' => 'etc'
],
[
'price' => [
'cost' => 500, 'tax' => 50, 'total' => 550
],
'otherKey' => 'etc'
],
[
'price' => [
'cost' => 600, 'tax' => 60, 'total' => 660
],
'otherKey' => 'etc'
],
];
becuase this can be done by using foreach, array_map() and array_column()
I have done it.
using array_column()
$result = array_column(array_column($array, 'price'), 'total');
printf($result);
in above i have to use array_column() two time that i don't want to use
using foreach
$result = [];
foreach ($array as $value) {
$result[] = $value['price']['total'];
}
printf($result);
this is working good but is there any better way.
is there any way that i can specify nested key in array_column() like
array_column($array, 'price.total'); // something like this
Result
array: [
0 => 210
1 => 550
2 => 660
]
i have searched but unable to find any question like this that's way i asked.
Thanks in Advance.
foreach is better way to do that even you can do a benchmark for performance you can have idea.
The simple foreach should do the job, you could also write a function which takes a string as input, splits it and retrieves the values from the array.
Another option which may be more ideal if:
the array structure gets a little too convoluted AND
as long as the key that you are trying to access is unique to the values that you are trying to target
is to use array_walk_recursive(). It will only visit "leafnodes" so it spares you from needing to check if an element is an array or not.
When used in this fashion, the output will be a flattened array.
Code: (Demo)
$totals = [];
array_walk_recursive(
$array,
function($leafNode, $key) use(&$totals) {
if ($key === 'total') {
$totals[] = $leafNode;
}
}
);
var_export($totals);
Output:
array (
0 => 210,
1 => 550,
2 => 660,
)
I am trying to take two arrays, and merge them to each other. The first array serves as an 'index' array, that is - that is the format that the output arrays desirably would be:
$array1 = [
'DIV1' => 'Some element data',
'SUPPLEMENTAL' => [
'RPC' => '10.24.122.32',
'PORT' => '8080'
],
'ASG' => 'some arbitrary data'
];
$array2 = [
'DIV2' => 'Some more element data',
'ASG' => 'different arbitrary data',
'DIV1' => 'Some element data that refers to the other object'
'SUPPLEMENTAL' => [
'RPC' => '10.24.123.1'
]
];
So after the merge, we would effectively have two arrays. This can be done as a a single function called twice, which passes each array as parameters (reversed for the second call - and somehow defining the index array). The keys would be carried over -only-, no values. We would end up with arrays looking like this:
$array1 = [
'DIV1' => 'Some element data',
'DIV2' => '', // blank because only key was moved
'SUPPLEMENTAL' => [
'RPC' => '10.24.122.32',
'PORT' => '8080'
],
'ASG' => 'some arbitrary data'
];
$array2 = [
'DIV1' => 'Some element data that refers to the other object'
'DIV2' => 'Some more element data',
'SUPPLEMENTAL' => [
'RPC' => '10.24.123.1',
'PORT' => '' // blank because only key was moved
],
'ASG' => 'different arbitrary data'
];
It is not -extremely- important that the imported (blank) keys are put in some order, but the preservation of order of existing elements is important. As long as it abides by the index arrays order definition (array1 in this case).
I think I would need to do some sort of nested sort for the multiple dimensions.
Because your data doesn't have keys in the same order it'll be difficult to maintain key order, but you can achieve what you need with a recursive function:
function recursiveReKeyArrays(array $array1, array $array2)
{
// Loop through the array for recursion
foreach ($array2 as $key => $value) {
if (!is_array($value)) {
continue;
}
$array1[$key] = recursiveReKeyArrays($array1[$key], $value);
}
// Find the differences in the keys
foreach (array_diff_key($array2, $array1) as $key => $value) {
$array1[$key] = null;
}
return $array1;
}
This will loop through the second array, find any values which are arrays and recurse into them and find any missing keys and set them to null.
This will give you this output:
Array
(
[DIV1] => Some element data
[SUPPLEMENTAL] => Array
(
[RPC] => 10.24.122.32
[PORT] => 8080
)
[ASG] => some arbitrary data
[DIV2] =>
)
Array
(
[DIV2] => Some more element data
[ASG] => different arbitrary data
[DIV1] => Some element data that refers to the other object
[SUPPLEMENTAL] => Array
(
[RPC] => 10.24.123.1
[PORT] =>
)
)
Example here: http://ideone.com/5ml1y4
i have this two arrays:
$array1 = [
'1' => 285.52,
'2' => 427.76
];
$array2 = [
'1' => 123.44,
'2' => 48.32
];
The keys on each of them are the id for the client, the first one is the amount owed and the second one is the amount payed, i want to achieve the following:
$mergedArrays = [
'1' => [
'owed' => 285.52,
'payed' => 123.44
],
'2' => [
'owed' => 427.76,
'payed' => 48.32
]
];
I was wondering if there's a PHP function to do so, i tried with array_merge_recursive but it just makes an array with the four elements together.
Any help would be really appreciated.
you can loop in the first array and merge the second according to keys
foreach($array1 as $key => $val) {
$mergedArrays[$key] = array('owed' => $val, 'payed' => $array2[$key]);
}
sample
$array1 = [
'1' => 285.52,
'2' => 427.76
];
$array2 = [
'1' => 123.44,
'2' => 48.32
];
$final_arr = array_map(function($a1, $a2) {
return array(
'owed' => $a1,
'paid' => $a2
);
}, $array1, $array2);
$final_arr = array_combine(array_keys($array1), $final_arr);
var_dump($final_arr);
Based on the comment, it seems you're looking for built-in PHP functions to do the task for you rather than going for traditional looping. But the looping method provided by Fabio is the simplest one you could go for without any other complicated approaches. I've tried my best to provide you the solution using the core PHP functions. Hope you're happy with it!
Short: Is there a way to get a named key/value from SUBARRAY without knowing the main key ?
Long:
Ive got a foreach loop that extracts text-files & turns them into individual / single arrays (resetting the array between each file)...
example:
Array
(
[Blah Blah] => Array
(
[number] => 10
[name] => nameBlah
[image] =>
)
)
Array
(
[pinkblue597] => Array
(
[number] => 18
[name] => nameBlah68
[image] =>
)
)
(the 1st part to turn into array is used by multiple parts of a process so I dont want to add unnecessary code)
I want to extract the value of "name" and "number", however I do not know the value / format of the key in advance.. - Example: pinkblue597
If I do print_r, I do see the array as I want...
print_r($found,true)."\n";
but if I do this, $name=$found[0]; I get no results for "$name"...
or
if I do this, $name=$found[0]["name"]; I get no results for "$name"...
I could do this via a foreach loop, but it seems inefficient...
PS there will only be ONE (unknown) key in this array, & a sub-array. The sub array is always the same.
Edited: made the code easier to see (forgot to do this)
If the array formation is going to be the same all the time...
then a (nested) foreach loop will suffice, take the example below,
<?php
$a = [
'somethingUnknown13582563' => [
'name' => 'name',
'number' => 15
],
'somethingUnknown2' => [
'name' => 'another name',
'number' => 24
]
];
foreach ($a as $key => $subArray) {
foreach ($subArray as $subKey => $value) {
echo $subArray[$subKey] . '<br>';
}
}
?>
Output
name
15
another name
24
Or...
You could use array_values,
<?php
$a = [
'somethingUnknown13582563' => [
'name' => 'first name',
'number' => 15
],
'somethingUnknown2' => [
'name' => 'name',
'number' => 24
]
];
$a = array_values($a);
echo $a[0]['name'];
?>
Which would turn the first associative array in to numeric indexes and would like so,
array(
0 => array(
'name' => 'first name',
'number' => 15,
),
1 => array(
'name' => 'name',
'number' => 24,
)
)
I'm not sure why you're creating a nested array in the first place if you only intend to discard it immediately, but since the array only appears to have a single element, and you only care about that element, you can simple use array_pop
$a = [
'somethingUnknown13582563' => [
'name' => 'first name',
'number' => 15
],
];
$data = array_pop($a);
echo $data['name']; // gives you 'first name'
Note that array_pop is destructive. So if you don't want this behavior you could use something like end instead.
$data = end($a); // same effect as array_pop but non-destructive
echo $data['name']; // also gives you 'first name'
With that said, the foreach construct isn't necessarily inefficient. I believe your true concern is around finding a simpler way to dereference the nested array. The easiest way to do that in your case is going to be using something like end($a)['name'] which gives you the kind of straight-forward dereferencing you're looking for.
You can use array_map() to achieve this...
array_map — Applies the callback to the elements of the given arrays. This will loop all the array elements through callback function and you can print each element present in the sub array..
<?php
$myArry = array(
'Blah Blah' => array(
'number' => 10,
'name' => 'Blah Blah 1',
),
'pinkblue597' => array(
'number' => 15,
'name' => 'Blah Blah 2',
)
);
array_map(function($arr){
echo 'Name : '.$arr['name'].'<br>';
echo 'Number : '.$arr['number'].'<br>';
},$myArry);
?>
This will give you :
Name : Blah Blah 1
Number : 10
Name : Blah Blah 2
Number : 15