I have the following array:
array(5) {
[0]=> array(3) {
[0]=> string(10) "2013-09-18"
[1]=> string(75) "Ready For Retina HD: Create Pixel-Perfect Assets For Multiple Scale Factors"
[2]=> string(74) "ready-for-retina-hd-create-pixel-perfect-assets-for-multiple-scale-factors"
}
[1]=> array(3) {
[0]=> string(10) "2010-10-20"
[1]=> string(40) "Taking A Closer Look At Tech Conferences"
[2]=> string(40) "taking-a-closer-look-at-tech-conferences"
}
[2]=> array(3) {
[0]=> string(10) "2014-10-19"
[1]=> string(29) "Wayfinding For The Mobile Web"
[2]=> string(29) "wayfinding-for-the-mobile-web"
}
[3]=> array(3) {
[0]=> string(10) "2014-05-15"
[1]=> string(24) "Freebie: Icons Of Autumn"
[2]=> string(23) "freebie-icons-of-autumn"
}
[4]=> &array(1){
[0]=> string(0) ""
}
}
How would I go about assigning key names to each part of the inner array? E,g date, title, pathname.
I understand you can do something like this to create an array with certain keys, but how does this work with multiple nested arrays? And how can it be assigned after array creation?
$keys = array('Date', 'Title', 'Filepath');
Assuming $array1 is your main array (with 5 values).
foreach($array1 as $a)
{
if (len($a) == 3)
$array2[] = array("Date" => $a[0], "Title" => $a[1], "Filepath" => $a[2]);
}
$array1 = $array2;
Use a foreach.
$new = [];
foreach ($origArray as $inner) {
$new[] = [
"date" => $inner[0],
"title" => $inner[1],
"filepath" => $inner[2]
];
}
$origArray = $new;
This doesn't handle cases where the item does not conform to the "standard" (e.g item 4) but this should get you started.
Related
I'm trying to loop through a multidimensional array with foreach but sometimes there's 5 dimensions and sometimes there's 2, but I need to foreach every array. Here is an example:
array(16) {
["id"]=>
string(2) "1"
["name"]=>
string(1) "Bob"
["job"]=>
array(2) {
[0]=>
string(8) "software"
[1]=>
string(7) "plumber"
}
["kids"]=>
array(2) {
[1]=>
array(2) {
[0]=>
string(4) "Jane"
[1]=>
string(4) "girl"
}
[2]=>
array(2) {
[0]=>
string(3) "Sam"
[1]=>
string(4) "boy"
[2] => array(2) {
[0]=>
string(3) "123"
[1]=>
string(11) "Main Street"
}
}
}
}
you get the point.... but imagine if I had a dimension of 10 in the array. How can I dynamically loop through them and do trim() to each value in the whole array?
Here is what I have so far:
foreach ($array as $key => $value) {
$array[$key] = trim($value);
}
but I need it to go deeper into an array if there is an array and perform trim to all values in my $array.
Edited
I get the combined item_ids now, but not the single item_ids.
I have an array with three keys.
$searchArray = {
[0]=> array(3) {
["keyword"]=> string(7) "history"
["url"]=> string(7) "history"
["item_id"]=> string(2) "16"
}
[1]=> array(3) {
["keyword"]=> string(4) "past"
["url"]=> string(4) "past"
["item_id"]=> string(2) "16"
}
[89]=> array(3) {
["keyword"]=> string(10) "biomedical"
["url"]=> string(10) "biomedical"
["item_id"]=> string(2) "34"
}
[93]=> array(3) {
["keyword"]=> string(10) "biomedical"
["url"]=> string(10) "biomedical"
["item_id"]=> string(2) "35"
}
I want to combine the options that have the same keyword/url.
Just need to check if keyword matches.
The final format needs to be something that jquery autocomplete can accept, where I can assign the text to keyword and the value to url, id to the item_id.
There were only two keys in the array before and I would combine matches this way.
foreach ($searchArray as $row)
{
$combineMatches[ $row['keyword'] ][] = $row['item_id'];
}
result after using json_encode():
"anthropologist":["27","37"],
"biomedical":["34","35"],
"m.s.":["18","19","23"]
What I currently have:
$combineMatches = array();
foreach ($searchArray as $row)
{
$match =
array_search($row['keyword'],array_column($combineMatches,'keyword'));
if($match){
$combineMatches[$match]['item_id']+= $row['item_id'];
}else{
array_push($combineMatches, [
'keyword' => $row['keyword'],
'url' => $row['url'],
'item_id' => array_push($row['item_id'])
]);
}
}
Result:
[7]=> array(3)
{
["keyword"]=> string(8) "theology"
["url"]=> string(8) "theology"
["item_id"]=> NULL
}
[13]=> array(3)
{
["keyword"]=> string(7) "writing"
["url"]=> string(7) "writing"
["item_id"]=> NULL
}
How do I add to the array column of just item_id ? Which I see is a string, but I need as an array.
This gets JSON encoded in the end of the PHP and read by jquery autocomplete.
Thank you for pointing out the string/array issue.
I changed how to add to the third key if there is a match, and if there isn't a match the solution was changing the array_push to just array.
$combineMatches = array();
foreach ($searchArray as $row)
{
$match=array_search($row['keyword'],array_column($combineMatches,'keyword'));
if($match){
$combineMatches[$match]['item_id'][] = $row['item_id'];
}else{
array_push($combineMatches, [
'keyword' => $row['keyword'],
'url' => $row['url'],
'item_id' => array($row['item_id'])
]);
}
}
I am new to PHP so be kind. :)
I have a 3 deep array. Something like this:
Array(5) {
[0]=> array(5) {
[0]=> string(0) ""
[1]=> string(21) "0,245.19000000,864432"
[2]=> string(21) "1,245.26000000,864432"
[3]=> string(21) "2,245.49000000,864432"
[4]=> string(21) "4,245.33000000,864432"
}
[1]=> array(5) {
[0]=> string(0) ""
[1]=> string(21) "0,245.19000000,864453"
[2]=> string(21) "1,245.26000000,864453"
[3]=> string(21) "2,245.49000000,864453"
[4]=> string(21) "4,245.33000000,864453"
}
}...
I want to explode the inner string by commas ("2,245.49000000,864453") so the arrays becomes 4 deep like so:
Array(5) {
[0]=> array(5) {
[0]=> string(0) ""
[1]=> array (3)
[0]=> "0"
[1]=> "245.19000000"
[2]=> "864432"
[2]=> array (3)
[0]=> "1"
[1]=> "245.26000000"
[2]=> "864432"
[3]=> array (3)
[0]=> "3"
[1]=> "245.49000000"
[2]=> "864432"
[4]=> array (3)
[0]=> "4"
[1]=> "245.3000000"
[2]=> "864432"
[4]=> array (3)
[0]=> "5"
[1]=> "245.3300000"
[2]=> "864432"
}
}
...
So far I have:
$done = array();
for ($i = 0; $i<=count($chunks); $i++) { //loops to get size of each 2d array
$r = count($chunks[$i]);
for ($c = 0; $c<=count($chunks[$r]); $c++) { //loops through 3d array
$arrayparts = $chunks[$i][$c];
$done[] = explode(",", $arrayparts); //$arrayparts is 3d array string that is exploded each time through loop
}
}
I think this code should work but when I var_dump nothing prints?
Can someone help me learn?
Thanks!
Suggested:
$chunks is 3d array
foreach($chunks as $innerArray) {
$result[] = array_map(function($v){
return explode(",", $v);
}, $innerArray);
}
Don't make it complicated, just use this:
(Here I go through each innerArray with a foreach loop and then I go through all values with array_map() and explode it and return it to the results array)
<?php
foreach($arr as $innerArray) {
$result[] = array_map(function($v){
return explode(",", $v);
}, $innerArray);
}
print_r($result);
?>
This uses array_map() two times. Maybe a better way but I'm on beer three:
$result = array_map(function($v){
return array_map(function($v){ return explode(',', $v); }, $v);
}, $array);
I have these 2 arrays $fonts['google'] and $data['value'] with the following content:
var_dump ($fonts['google']) outputs
array(4) {
[0]=> array(3) { ["family"]=> string(7) "ABeeZee" ["variants"]=> array(2) { [0]=> string(7) "regular" [1]=> string(6) "italic" } ["subsets"]=> array(1) { [0]=> string(5) "latin" } }
[1]=> array(3) { ["family"]=> string(4) "Abel" ["variants"]=> array(1) { [0]=> string(7) "regular" } ["subsets"]=> array(1) { [0]=> string(5) "latin" } }
[2]=> array(3) { ["family"]=> string(13) "Abril Fatface" ["variants"]=> array(1) { [0]=> string(7) "regular" } ["subsets"]=> array(2) { [0]=> string(5) "latin" [1]=> string(9) "latin-ext" } }
[3]=> array(3) { ["family"]=> string(8) "Aclonica" ["variants"]=> array(1) { [0]=> string(7) "regular" } ["subsets"]=> array(1) { [0]=> string(5) "latin" } }
}
var_dump ($data['value']) outputs
array(4) {
["size"]=> int(17)
["family"]=> string(3) "Exo"
["style"]=> string(3) "200"
["subsets"]=> string(5) "latin"
}
Now I get the $data['value']['family'] = 'Abel' from my database.
Questions:
How can I get the ['variants'] for the given $data['value']['family'] value?
How can I get the index in $fonts['google'] for the sub-array where the $data['value']['family'] value is?
PHP supports Associative Arrays which let you use a (string) key rather than a numeric index for each element. These arrays are akin to javascript objects, Objective-C dictionaries, java HashMaps, etc.
That makes scenarios like this easy. Do you have control over building the original data array? If you can refactor your storage, set up the arrays like this:
$fonts['google'] = [
["ABeeZee"] => [
["variants"]=>["regular", "italic"],
["subsets"]=>["latin"]
],
["Abel"] => [
["variants"]=>["regular"],
["subsets"]=>["latin"]
],
["Abril Fatface"] => [
["variants"]=>["regular"],
["subsets"]=>["latin", "latin-ext"]
],
["Aclonica"] => [
["variants"]=>["regular"],
["subsets"]=>["latin"]
]
]
extra credit: if you have the original data as in the post, you could convert it:
$newArray = array(); // or just [] in PHP >= 5.3 I believe
foreach($fonts['google'] as $index=>$fontArray) {
$newArray[$fontArray['family']] = $fontArray;
// this leaves a redundant copy of the family name in the subarray
unset $newArray[$fontArray['family']]['family']; // if you want to remove the extra copy
}
Then it becomes trivial. Given a font family name, you just access $fonts['google'][$fontFamilyName] (or $newArray[$fontFamilyName]) using the family name as the array index.
I have an array that contains 4 arrays with one value each.
array(4) {
[0]=>
array(1) {
["email"]=>
string(19) "test01#testmail.com"
}
[1]=>
array(1) {
["email"]=>
string(19) "test02#testmail.com"
}
[2]=>
array(1) {
["email"]=>
string(19) "test03#testmail.com"
}
[3]=>
array(1) {
["email"]=>
string(19) "test04#testmail.com"
}
}
What is the best (=shortest, native PHP functions preferred) way to flatten the array so that it just contains the email addresses as values:
array(4) {
[0]=>
string(19) "test01#testmail.com"
[1]=>
string(19) "test02#testmail.com"
[2]=>
string(19) "test03#testmail.com"
[3]=>
string(19) "test04#testmail.com"
}
In PHP 5.5 you have array_column:
$plucked = array_column($yourArray, 'email');
Otherwise, go with array_map:
$plucked = array_map(function($item){ return $item['email'];}, $yourArray);
You can use a RecursiveArrayIterator . This can flatten up even multi-nested arrays.
<?php
$arr1=array(0=> array("email"=>"test01#testmail.com"),1=>array("email"=>"test02#testmail.com"),2=> array("email"=>"test03#testmail.com"),
3=>array("email"=>"test04#testmail.com"));
echo "<pre>";
$iter = new RecursiveIteratorIterator(new RecursiveArrayIterator($arr1));
$new_arr = array();
foreach($iter as $v) {
$new_arr[]=$v;
}
print_r($new_arr);
OUTPUT:
Array
(
[0] => test01#testmail.com
[1] => test02#testmail.com
[2] => test03#testmail.com
[3] => test04#testmail.com
)