PHP. How to extract array keys for new array? - php

How can I extract server_vps_de_dc1_s1 from this array:
$server = array(
"vps" => array (
"de" => array (
"dc1" => array (
"s1" => array (
"name"=> "Xen VPS 200",
"processor"=> "200 MHz",
"memory"=> "200 MB",
),
),
),
),
"dedicated" => array (
...
),
);
to build new array that should looks like this one:
$server_id = array(
"1" => "server_vps_de_dc1_s1",
"2" => "server_vps_de_dc1_s2",
"3" => "server_vps_de_dc2_s1",
"4" => "server_vps_usa_dc1_s1",
...
);

You'll need recursion:
function get_keys( $array)
{
if( !is_array( $array))
return array();
$k = key( $array);
return array_merge( array( $k), get_keys( $array[$k]));
}
You'd invoke it like this:
$keys = get_keys( $array);
array_pop( $keys); // Get rid of the last key:
And you get as output:
array(4) { [0]=> string(3) "vps" [1]=> string(2) "de" [2]=> string(3) "dc1" [3]=> string(2) "s1" }
Which you can form your new values with implode():
$new_value = implode( '_', $keys); // Outputs "vps_de_dc1_s1"
Demo

Related

Multi-dimentional array how to get the nested value without foreach loop

I got output from one of the WordPress table cells. The following value is displayed.
$allcoinkey=get_option('_transient_mcw-custom-data');
var_dump($allcoinkey);
and the output:
[0]=>
array(2) {
["slug"]=>
string(7) "bitcoin"
["keywords"]=>
string(30) "بیتکوین,بیت کوین"
}
[1]=>
array(2) {
["slug"]=>
string(8) "ethereum"
["keywords"]=>
string(27) "اتریوم,اتاریوم"
}
}
How do I access keyword values where slug=bitcoin without foreach?
i use this sample code:
<?php
$array = array(0 => 'blue', 1 => 'red', 2 => 'green', 3 => 'red');
$key = array_search('green', $array); // $key = 2;
$key = array_search('red', $array); // $key = 1;
?>
You can do it like this:
<?php
$allcoinkey = [
[
'slug' => 'bitcoin',
'keywords' => 'بیتکوین,بیت کوین',
],
[
'slug' => 'ethereum',
'keywords' => 'اتریوم,اتاریوم',
],
];
$bitcoinKeywords = current(array_filter($allcoinkey, static function (array $cryptoCurrency) {
return $cryptoCurrency['slug'] === 'bitcoin';
}))['keywords'];
echo $bitcoinKeywords;

array_combine results only one result [duplicate]

This question already has answers here:
array_combine is return only last value
(2 answers)
Closed 3 years ago.
I am using the following code to get two arrays into one json result. But getting only the first index as result. Is there any error in the code or anybody can suggest an alternate method to get the same result.
$array1 = $_POST['array1'];
$array2 = $_POST['array2'];
$jsonArray = array();
foreach (array_combine( $array1, $array2 ) as $name => $value) {
$jsonArray[] = array('name' => $name, 'value' => $value);
}
echo $json = json_encode($jsonArray);
$_POST['array1'] = array(4) {
[0]=>
string(3) "day1"
[1]=>
string(3) "day2"
[2]=>
string(3) "day3"
[3]=>
string(3) "day4"
}
$_POST['array2'] = array(4) {
[0]=>
string(3) "item1"
[1]=>
string(3) "item2"
[2]=>
string(3) "item3"
[3]=>
string(3) "item4"
}
Expected result should be like
[{"name":"day1","value":"item1"},{"name":"day2","value":"item2"},{"name":"day3","value":"item3"}]
Try this,
$arr1 = array('0' => 'day1', '1' => 'day2', '2' => 'day3', '3' => 'day4');
echo'<pre>';print_r($arr1);
$arr2 = array('0' => 'item1','1' => 'item2','2' => 'item3','3' => 'item4');
echo'<pre>';print_r($arr2);
echo'<pre>';print_r(array_combine($arr1, $arr2));
$newArray = array();
foreach(array_combine($arr1, $arr2) as $key => $value){
array_push($newArray, array('name'=> $key,'value'=>$value));
}
echo'<pre>';print_r($newArray);
echo json_encode($newArray);die;

How can I print the lowest key of an array?

This is my array:
array(4) {
["1"]=>
array(3) {
[0]=>
string(2) "01"
[1]=>
string(2) "02"
[2]=>
string(2) "03"
}
["2"]=>
array(2) {
[0]=>
string(2) "01"
[1]=>
string(2) "02"
}
["3"]=>
array(1) {
[0]=>
string(2) "01"
}
["4"]=>
array(1) {
[0]=>
string(2) "01"
}
}
I want to print the lowest key, but only from the keys, that have less than 3 values.
echo min(array_keys($myarray));
gives me the result: 1
But key 1 already has 3 values, so the result I would need is 2. In the case every key has 3 values then print the next key (in this case would be 5)
I do not know how to do this. I am happy for every hint or advise.
This function iterate over your array and looks for all keys that has a value less then 3 values. It will return the first it founds if none is found the next key is return.
function getLowestKeyWithLessThan($yourArray, $number=3)
{
foreach ($yourArray as $key => $value) {
if (count($value) < $number)
return $key;
}
return count($yourArray) + 1;
}
If I run the following lines:
print "Answer " . getLowestKeyWithLessThan($yourArray);
print "\nAnswer " . getLowestKeyWithLessThan($AllKeysHasThreeElements);
This gives the answer:
Answer 2
Answer 5
Here is the data I used to test this:
$yourArray = array(
"1"=> array(
'0' => "01",
'1' => "02",
'2' => "03",
),
"2"=> array(
'0' => "01",
'1' => "02",
),
"3"=> array(
'0' => "01",
),
"4"=> array(
'0' => "01",
),
);
$threeValues = array(
'0' => "01",
'1' => "02",
'2' => "03",
);
$AllKeysHasThreeElements = array(
"1"=> $threeValues,
"2"=> $threeValues,
"3"=> $threeValues,
"4"=> $threeValues,
);
Of course the data could also been written like this:
$threeValues = array("01", "02", "03");
$yourArray = array($threeValues, array("01", "02"), array("01"), array("01"));
$AllKeysHasThreeElements = array($threeValues,$threeValues,$threeValues,$threeValues);

Merging arrays with specific output format

I am currently learning how to manage and work with arrays. But I am a bit lost with combining two arrays. Both arrays have the same number of values in it. The array_merge( $thumbnails, $urls ); does what it says but it is not what I am looking for. How can i merge the array as shown below?
$thumbnails = array(
array( "thumbnail" => "https://example1.png" ) ,
array( "thumbnail" => "https://example2.png" ) ,
array( "thumbnail" => "https://example3.png" ) ,
);
$urls = array(
array( "url" => "http://www.example.com/1" ) ,
array( "url" => "http://www.example.com/2" ) ,
array( "url" => "http://www.example.com/3" ) ,
);
Current Result
[0]=>
array(1) {
["thumbnail"]=> "https://example1.png"
}
[1]=>
array(1) {
["thumbnail"]=> "https://example2.png"
}
[2]=>
array(1) {
["thumbnail"]=> "https://example3.png"
}
[3]=>
array(1) {
["url"]=> "http://www.example.com/1"
}
[4]=>
array(1) {
["url"]=> "http://www.example.com/2"
}
[5]=>
array(1) {
["url"]=> "http://www.example.com/3"
}
Desired Result
[0]=>
array(2) {
["thumbnail"]=> "https://example1.png"
["url"]=> "http://www.example.com/1"
}
[1]=>
array(2) {
["thumbnail"]=> "https://example2.png"
["url"]=> "http://www.example.com/2"
}
[2]=>
array(2) {
["thumbnail"]=> "https://example2.png"
["url"]=> "http://www.example.com/2"
}
[3]=>
array(2) {
["thumbnail"]=> "https://example3.png"
["url"]=> "http://www.example.com/3"
}
I would just loop over them:
foreach ($thumbnails as $k => $src) {
if (isset($urls[$k]) {
$urls[$k]['thumbnail'] = $src;
}
}
The function array_merge won't help you out here, because it's "Array in Array". But you can loop over them, so you have only one array-item. The following function returns an array just as you desire:
function array_merge_keys($a, $b) {
$retArr = array();
// Lets use min(countA, countB) so there will be no errors on
// unbalanced array item counts.
for($i = 0; $i < min(count($a), count($b)); $i++) {
$retArr[$i] = array_merge($a[$i], $b[$i]);
} // for end
return $retArr;
}
$a = array(array("url" => "1.jpg"), array("url" => "2.jpg"));
$b = array(array("thumb" => "1.thumb.jpg"), array("thumb" => "2.thumb.jpg"));
print_r(array_merge_keys($a, $b));
This gives you:
Array
(
[0] => Array
(
[url] => 1.jpg
[thumb] => 1.thumb.jpg
)
[1] => Array
(
[url] => 2.jpg
[thumb] => 2.thumb.jpg
)
)
$thumbnails = array(
array( "thumbnail" => "https://example1.png" ) ,
array( "thumbnail" => "https://example2.png" ) ,
array( "thumbnail" => "https://example3.png" ) ,
);
$urls = array(
array( "url" => "http://www.example.com/1" ) ,
array( "url" => "http://www.example.com/2" ) ,
array( "url" => "http://www.example.com/3" ) ,
);
$thumbnails = array_combine(array_map(function($key){return 'key'.$key;},array_keys($thumbnails)),$thumbnails);
$urls = array_combine(array_map(function($key){return 'key'.$key;},array_keys($urls)),$urls);
var_dump(array_values(array_merge_recursive($thumbnails,$urls)));
do you mean this ?

Can't declare keys in two dimensional array in PHP

When i try to generate array, like this way:
$files_array = array(
'name' => array(),
'path' => array()
);
and then assign them values:
$files_array['name'][] = $fileinfo->getFilename();
$files_array['path'][] = $pathname;
the var_dump() function return me an array with numeric keys instead of "name" and "path", like this:
array(2) { [0]=> array(0) { } [1]=> array(0) { } }
What's wrong with the array? I've tried several way of doing this, but none give me my desired array.
EDIT:
A filled array dump, with the same code:
array(2) { [0]=> array(3) { [0]=> string(44) "./upload/4//lol/Nuovo documento di testo.TXT" [1]=> string(51) "./upload/4//lol/blue_bokeh_4-wallpaper-1366x768.jpg" [2]=> string(29) "./upload/4//lol/menny €.txt" } [1]=> array(3) { [0]=> string(28) "Nuovo documento di testo.TXT" [1]=> string(35) "blue_bokeh_4-wallpaper-1366x768.jpg" [2]=> string(13) "menny €.txt" } }
EDIT:
My full code
$files_array = array(
'name' => array(),
'path' => array()
);
$fileinfos = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($rootpath)
);
foreach ($fileinfos as $pathname => $fileinfo) {
if (!$fileinfo->isFile())
continue;
$files_array['name'][] = $fileinfo->getFilename();
$files_array['path'][] = $pathname;
}
That's how it works:
<?php
$files_array = array();
$i = 0;
$files_array[$i]['name'] = $fileinfo->getFilename();
$files_array[$i]['path'] = $pathname;
$i++;
The result output will be like:
array (size=2)
0 =>
array (size=2)
'name' => string 'file' (length=4)
'path' => string '/foo/' (length=5)
1 =>
array (size=2)
'name' => string 'file2' (length=5)
'path' => string '/bar/' (length=5)
I would suggest reading the php manual on arrays. Here are some examples.
//1
$files_array = array();
$files_array['name'] = array();
$files_array['path'] = array();
//2
$files_array = array(
'name' => [],
'path' => []
);

Categories