PHP remove nested arrays - php

I have an array $templates that looks like this:
Array
(
[0] => Array
(
[displayName] => First Template
[fileName] => path_to_first_template
)
[1] => Array
(
[displayName] => Second Template
[fileName] => path_to_second_template
)
[2] => Array
(
[displayName] => Third template
[fileName] => path_to_third_template
)
)
And I want to make it to look like this:
Array
(
[path_to_first_template] => First Template
[path_to_second_template] => Second Template
[path_to_third_template] => Third Template
)
That is, I want the fileName of the nested arrays to be the new array's key and displayName to be its value.
Is there a pretty way to do this without having to loop through the array. I had no luck searching, as I didn't know exactly what to search for.

Here's a classic foreach in action:
$result = array();
foreach($array as $row) {
$result[$row['fileName']] = $row['displayName'];
};
Here's a "clever" way to do it:
$result = array();
array_walk($array, function($row) use (&$result) {
$result[$row['fileName']] = $row['displayName'];
});
As you can see, the second approach is not really better than the first one. The only advantage is that theoretically you can pile upon the second form because it is a single expression, but in practice it's a long enough expression already so you wouldn't want to do that.

Loop in your array and make a new one:
$newArray = array();
foreach($array as $val){
$newArray[$val['fileName']] = $val['displayName'];
}
print_r($newArray);

$ret = array()
foreach ($templates as $template) {
$ret[$template["fileName"]] = $template["displayName"];
}

Related

How to extract element inside an array, which in turn is inside a couple of arrays and display it using a foreach loop

I have a result of a query, which is the name of the image. I am storing the image names for every image Id in an array. Now, on the view page I am using foreach loop to display these images. The problem is I can't extract the elements(the name of the images) from this array.
My array is
Array ( [0] => Array ( [0] => Array ( [picture] => 5a3a13f237715637629.jpeg ) ) [1] => Array ( [0] => Array ( [picture] => 5a3b602654cfd527057.jpg ) ) )
I have used print_r and got this, now I want to extract only the 5a3a13f237715637629.jpeg values and display these using foreach loop on the view page. Any help is welcome.
The simplest way I can think of would be to json the array and then use regex to extract the filenames. You are then left with an array of filenames to loop through and display:
preg_match('/\w+.jpeg/', json_encode($array), $matches);
print_r($matches);
The benefits of doing it this way are that you don't need to know the structure of the array or go through embedded looping to find the values.
If you want do want the loop way; try this:
$array = array(
1 => array(
'picture' => '5a3a13f237715637629.jpeg'
),
2 => array(
'picture' => 'fnofweofweiofniewof.jpeg'
)
);
print_r(search_r($array, 'picture', $results));
function search_r($array, $key, &$results) {
if (!is_array($array)) {
return;
}
if (isset($array[$key])) {
$results[] = $array[$key];
}
foreach ($array as $subarray) {
search_r($subarray, $key, $results);
}
return $results;
}
That will result:
Array
(
[0] => 5a3a13f237715637629.jpeg
[1] => fnofweofweiofniewof.jpeg
)
PS. This is an adaption of this answer

Setting a ++ number variable as the array key

I have this code right now, it fetches the date and time. I wanted to create kind of a numbered index because I get back about 10 date and times in that one foreach loop. It's in a function and I need to return this array to do something with it elsewhere.
$i = 0;
foreach ($data as $key =>$value) {
$new_data = array (
$i => array (
"date"=> $value->DATE,
"time"=> $value->TIME,
)
);
$i++;
}
I wanted it to look more like this
Array (
[0] => Array (
[date] => whatever date
[time] => whatever time
)
[1] => Array (
[date] => whatever date
[time] => whatever time
)
[2] .. etc
)
Turns out that's not what I'm getting. I get this.
Array (
[10] => Array (
[date] => whatever date
[time] => whatever time
)
It only prints out in one / just gives me the tenth. How would I get it to keep ++ing the $i variable to allow me to get it in the numbered indices? Why is it only showing me the tenth?
You probably wanted just this:
$new_data = array();
foreach ($data as $value) {
$new_data[] = array (
"date"=> $value->DATE;
"time" => $value->TIME;
);
}
First, without [], you just assign a new value to $new_data variable at each iteration. With it, you append a new element to an array at each step; that's obviously what should be done in this case.
Second, you don't have to use another variable in this case: indexing starts from 0, and with each new [] increases as it should be.
Finally (kudos to #reformed for mentioning that in comments), you don't have to write long form of foreach if you actually don't use array's keys. foreach $arr as $val is sufficient.
In my opinion, that may be rewritten more concise with array_map:
$new_data = array_map(function($val) { return array(
'date' => $val->DATE,
'time' => $val->TIME
); }, $data);
This function usually is quite a fit when one wants to create a normal array based on another array, and each element of this new array is somehow based on the corresponding element of the original collection.
I've used an anonymous function here as an argument of array_map, that's available since PHP 5.3.
$i = 0;
foreach ($data as $key =>$value) {
$new_data[$i++] = array (
"date"=> $value->DATE;
"time" => $value->TIME;
)
);
}

PHP Convert multidimensional array to match format of another

I have two arrays, one is generated by using explode() on a comma separated string and the other is generated from result_array() in Codeigniter.
The results when doing print_r are:
From explode():
Array
(
[0] => keyword
[1] => test
)
From database:
Array
(
[0] => Array
(
[name] => keyword
)
[1] => Array
(
[name] => test
)
)
I need them to match up so I can use array_diff(), what's the best way to get them to match? Is there something other than result_array() in CI to get a compatible array?
You could create a new array like this:
foreach($fromDatabase as $x)
{
$arr[] = $x['name'];
}
Now, you will have two one dim arrays and you can run array_dif.
$new_array = array();
foreach ($array1 as $line) {
$new_array[] = array('name' => $line);
}
print_r($new_array);
That should work for you.

Convert PHP array into Key => Value Array

Total PHP Noob and I couldn't find an answer to this specific problem. Hope someone can help!
$myvar is an array that looks like this:
Array (
[aid] => Array (
[0] => 2
[1] => 1
)
[oid] => Array(
[0] => 2
[1] => 1
)
)
And I need to set a new variable (called $attributes) to something that looks like this:
$attributes = array(
$myvar['aid'][0] => $myvar['oid'][0],
$myvar['aid'][1] => $myvar['oid'][1],
etc...
);
And, of course, $myvar may contain many more items...
How do I iterate through $myvar and build the $attributes variable?
use array_combine()
This will give expected result.
http://php.net/manual/en/function.array-combine.php
Usage:
$attributes = array_combine($myArray['aid'], $myArray['oid']);
Will yield the results as requested.
Somthing like this if I understood the question correct
$attributes = array();
foreach ($myvar['aid'] as $k => $v) {
$attributes[$v] = $myvar['oid'][$k];
}
Your requirements are not clear. what you mean by "And, of course, $myvar may contain many more items..." there is two possibilties
1st. more then two array in main array. like 'aid', 'oid' and 'xid', 'yid'
2nd. or two main array with many items in sub arrays like "[0] => 2 [1] => 1 [2] => 3"
I think your are talking about 2nd option if so then use following code
$aAid = $myvar['aid'];
$aOid = $myvar['oid'];
foreach ($aAid as $key => $value) {
$attributes['aid'][$key] = $value;
$attributes['oid'][$key] = $myvar['oid'][$key];
}
You can itterate though an array with foreach and get the key and values you want like so
$attributes = array()
foreach($myvar as $key => $val) {
$attributes[$key][0] = $val;
}

Counting distinct values in a multidimensional array

I have an array that looks like the one below. I'm trying to group and count them, but haven't been able to get it to work.
The original $result array looks like this:
Array
(
[sku] => Array
(
[0] => 344
[1] => 344
[2] => 164
)
[cpk] => Array
(
[0] => d456
[1] => d456
)
)
I'm trying to take this and create a new array:
$item[sku][344] = 2;
$item[sku][164] = 1;
$item[cpk][d456] = 1;
I've gone through various iterations of in_array statements inside for loops, but still haven't been able to get it working. Can anyone help?
I wouldn't use in_array() personally here.
This just loops through creating the array as it goes.
It seems to work without needing to first set the index as 0.
$newArray = array();
foreach($result as $key => $group) {
foreach($group as $member) {
$newArray[$key][$member]++;
}
}

Categories