How to get sub array in PHP?

Asked
Active3 hr before
Viewed126 times

9 Answers

array
90%

Meta Stack Overflow , Stack Overflow Public questions & answers , Stack Overflow help chat ,Stack Overflow en español

$subArray = array_slice($arr, 0, 4);
load more v
88%

array_slice() returns the sequence of elements from the array array as specified by the offset and length parameters. , Returns the slice. If the offset is larger than the size of the array, an empty array is returned. ,array_splice() - Remove a portion of the array and replace it with something else, If the array is shorter than the length, then only the available array elements will be present.

Array
   (
      [0] => c[1] => d
   )
Array
   (
      [2] => c[3] => d
   )
load more v
72%

array_slice($array, 0, 50); // same as offset 0 limit 50 in sql
load more v
65%

array_rotate_category() is like array_rotate() only it avoids clobbering duplicate values of $subkey by creating "category" array containters for each possible value of $subkey. This additional array container will be created even if there is only one sub-key with a particular value (and would not have caused a collision).,array_flatten() makes a two-dimensional into one-dimension while retaining sequential order. Both the top and second level arrays have their integer keys re-indexed to in consecutive sequence.,array_rotate() is like array_flip() only it's for Two-dimensional arrays. There can be more than two dimensions but the value of $subkey can't be another array and must be a valid key.,array_rotate_jagged() is an adaptive version of array_rotate_category() meaning it will create a category only if a collision would occur. This means that the final array returned is "jagged" meaning each element might have a diffent dimensional depth (could be a single array or an array of arrays).

ISSUE: you want the value of 'subkey' below to be the keys of the array. Also (although might not tell simply by looking) the current keys are error codes and you want to rotate them into the subarray elements under the key 'code', replacing the 'subkey' element which will not be the outer-most keys.

$by_code = array(
  404 => ['subkey'=>'subkey-val-DOH','subkey2'=>'subkey2-val-1'],
  302 => ['subkey'=>'subkey-val-one','subkey2'=>'subkey2-val-2'],
  418 => ['subkey'=>'subkey-val-DOH','subkey2'=>'subkey2-val-3'],
  422 => ['subkey'=>'subkey-val-two','subkey2'=>'subkey2-val-4'],
);
function pretty_print($a){echo json_encode($a,JSON_PRETTY_PRINT)."\n<hr>\n";}

array_rotate() is like array_flip() only it's for Two-dimensional arrays. There can be more than two dimensions but the value of $subkey can't be another array and must be a valid key.

pretty_print(array_rotate($by_code, 'subkey', 'code'));

output:

[
   "subkey-val-DOH" => ["subkey2" => "subkey2-val-3", "code" => 404],
   "subkey-val-one" => ["subkey2" => "subkey2-val-2", "code" => 302]
   "subkey-val-two" => ["subkey2" => "subkey2-val-4", "code" => 422],
]

array_rotate_category() is like array_rotate() only it avoids clobbering duplicate values of $subkey by creating "category" array containters for each possible value of $subkey. This additional array container will be created even if there is only one sub-key with a particular value (and would not have caused a collision).

pretty_print(array_rotate_category($by_code, 'subkey', 'code'));

output:

[
   "subkey-val-DOH" => [
      0 => ["subkey2" => "subkey2-val-1", "code" => 404],
      1 => ["subkey2" => "subkey2-val-3", "code" => 404]
   ],
   "subkey-val-one" => [
      0 => ["subkey2" => "subkey2-val-2", "code" => 302]
   ],
   "subkey-val-two" => [
      0 => ["subkey2" => "subkey2-val-4", "code" => 422]
   ]
]

array_rotate_jagged() is an adaptive version of array_rotate_category() meaning it will create a category only if a collision would occur. This means that the final array returned is "jagged" meaning each element might have a diffent dimensional depth (could be a single array or an array of arrays).

pretty_print(array_rotate_jagged($by_code, 'subkey', 'code'));

output:

[
   "subkey-val-DOH" => [
      0 => ["subkey2" => "subkey2-val-1", "code" => 404]
      1 => ["subkey2" => "subkey2-val-3", "code" => 418]
   ],
   "subkey-val-one" => ["subkey2" => "subkey2-val-2", "code" => 302],
   "subkey-val-two" => ["subkey2" => "subkey2-val-4", "code" => 422]
]

create_rotations() is the en masse version of array_rotate().

pretty_print(create_rotations($by_code, 'code'));

output:

[
   "code" => [
      404 => ["subkey" => "subkey-val-DOH", "subkey2" => "subkey2-val-1"],
      302 => ["subkey" => "subkey-val-one", "subkey2" => "subkey2-val-2"],
      418 => ["subkey" => "subkey-val-DOH", "subkey2" => "subkey2-val-3"],
      422 => ["subkey" => "subkey-val-two", "subkey2" => "subkey2-val-4"]
   ],
   "subkey" => [
      "subkey-val-DOH" => ["subkey2" => "subkey2-val-3", "code" => 404],
      "subkey-val-one" => ["subkey2" => "subkey2-val-2", "code" => 302],
      "subkey-val-two" => ["subkey2" => "subkey2-val-4", "code" => 422]
   ],
   "subkey2" => [
      "subkey2-val-1" => ["subkey" => "subkey-val-DOH", "code" => 404],
      "subkey2-val-2" => ["subkey" => "subkey-val-one", "code" => 302],
      "subkey2-val-3" => ["subkey" => "subkey-val-DOH", "code" => 418],
      "subkey2-val-4" => ["subkey" => "subkey-val-two", "code" => 422]
   ]
]

NOTE: The primary key (if provided) is still "array-ified" when the lookup table sort is created for it EVEN though collisions are not possible. This is so you have a universal way of dealing with lookups (you will always the same depths of arrays.) In other words even thought there should be only one "result" if you search by primary key, you will get an array with one value.

pretty_print(create_sorts($by_code, 'code'));

output:

[
   "code" => [
      404 => [
         0 => ["subkey" => "subkey-val-DOH", "subkey2" => "subkey2-val-1"]
      ],
      302 => [
         0 => ["subkey" => "subkey-val-one", "subkey2" => "subkey2-val-2"]
      ],
      418 => [
         0 => ["subkey" => "subkey-val-DOH", "subkey2" => "subkey2-val-3"]
      ],
      422 => [
         0 => ["subkey" => "subkey-val-two", "subkey2" => "subkey2-val-4"]
      ]
   ],
   "subkey" => [
      "subkey-val-DOH" => [
         0 => ["subkey2" => "subkey2-val-1", "code" => 404],
         1 => ["subkey2" => "subkey2-val-3", "code" => 418]
      ],
      "subkey-val-one" => [
         0 => ["subkey2" => "subkey2-val-2", "code" => 302]
      ],
      "subkey-val-two" => [
         0 => ["subkey2" => "subkey2-val-4", "code" => 422]
      ]
   ],
   "subkey2" => [
      "subkey2-val-1" => [
         0 => ["subkey" => "subkey-val-DOH", "code" => 404]
      ],
      "subkey2-val-2" => [
         0 => ["subkey" => "subkey-val-one", "code" => 302]
      ],
      "subkey2-val-3" => [
         0 => ["subkey" => "subkey-val-DOH", "code" => 418]
      ],
      "subkey2-val-4" => [
         0 => ["subkey" => "subkey-val-two", "code" => 422]
      ]
   ]
]

create_sorts_jagged() is the en masse version of array_rotate_jagged().

pretty_print(create_sorts_jagged($by_code, 'code'));

output:

[
   "code" => [
      404 => ["subkey" => "subkey-val-DOH", "subkey2" => "subkey2-val-1"],
      302 => ["subkey" => "subkey-val-one", "subkey2" => "subkey2-val-2"],
      418 => ["subkey" => "subkey-val-DOH", "subkey2" => "subkey2-val-3"],
      422 => ["subkey" => "subkey-val-two", "subkey2" => "subkey2-val-4"]
   ],
   "subkey" => [
      "subkey-val-DOH" => [
         0 => ["subkey2" => "subkey2-val-1", "code" => 404],
         1 => ["subkey2" => "subkey2-val-3", "code" => 418]
      ],
      "subkey-val-one" => ["subkey2" => "subkey2-val-2", "code" => 302],
      "subkey-val-two" => ["subkey2" => "subkey2-val-4", "code" => 422]
   ],
   "subkey2" => [
      "subkey2-val-1" => ["subkey" => "subkey-val-DOH", "code" => 404],
      "subkey2-val-2" => ["subkey" => "subkey-val-one", "code" => 302],
      "subkey2-val-3" => ["subkey" => "subkey-val-DOH", "code" => 418],
      "subkey2-val-4" => ["subkey" => "subkey-val-two", "code" => 422]
   ]
]

create_sorts_jagged() is the en masse version of array_rotate_jagged().

pretty_print(subarray_search($by_code, 'subkey', 'subkey-val-DOH'));

output:

[
   404,
   418
]

create_sorts_jagged() is the en masse version of array_rotate_jagged().

echo subarray_find($by_code, 'subkey', 'subkey-val-DOH');

output:

404
$argv = [
   'arg0 value',
   'arg1 value',
   'arg2 value',
   ['arg3[0] key' => 'arg3[0] value',
      'arg3[1] key' => 'arg3[1] value',
   ],
   'arg4 value',
   ['arg5[0] value',
      'arg5[1] key' => 'arg5[1] value'
   ]
];
$arr = array_flatten($argv, true, false);
echo json_encode($arr, JSON_PRETTY_PRINT);

output:

{
   "0": "arg0 value",
   "1": "arg1 value",
   "2": "arg2 value",
   "arg3[0] key": "arg3[0] value",
   "arg3[1] key": "arg3[1] value",
   "4": "arg4 value",
   "5": "arg5[0] value",
   "arg5[1] key": "arg5[1] value"
}
$arr = merge_subarrays($argv, true, false);
echo json_encode($arr, JSON_PRETTY_PRINT);

output:

{
   "top": {
      "0": "arg0 value",
      "1": "arg1 value",
      "2": "arg2 value",
      "4": "arg4 value"
   },
   "sub": {
      "arg3[0] key": "arg3[0] value",
      "arg3[1] key": "arg3[1] value",
      "0": "arg5[0] value",
      "arg5[1] key": "arg5[1] value"
   }
}
function test() {
   extract(argv_and_vars());
   echo "argv: ".json_encode($argv, JSON_PRETTY_PRINT);
   echo "vars: ".json_encode($vars, JSON_PRETTY_PRINT);
   extract($vars);
   echo '$var1 '.$var1.
   "\n";
   echo '$var2 '.$var2.
   "\n";
   echo '$var3 '.$var3.
   "\n";
}

$named_args = array('var1' => 'var1 value', 'var2' => 'var2 value');
$one_more = array('var3' => 'var3 value');
test('arg0', 'arg1', 'arg2', $named_args, 'arg4', $one_more);

output:

argv: {
   "0": "arg0",
   "1": "arg1",
   "2": "arg2",
   "4": "arg4"
}
vars: {
   "var1": "var1 value",
   "var2": "var2 value",
   "var3": "var3 value"
}
$var1 var1 value
$var2 var2 value
$var3 var3 value
load more v
75%

Given an unsorted array of nonnegative integers, find a continuous subarray which adds to a given number. Examples : ,Find the smallest positive integer value that cannot be represented as sum of any subset of a given array,Find subarray with given sum | Set 1 (Nonnegative Numbers),Find subarray with given sum with negatives allowed in constant space

40%

i want to take index-id to main array key my array must be like this,I have an array. This array have a sub arrays. I want to take sub array value to main array keys. Here is my example array: ,Where $temp is result array, $arr is your array.,To retain ALL subarray data, use null as the 2nd argument.

I have an array. This array have a sub arrays. I want to take sub array value to main array keys. Here is my example array:

Array
   (
      [0] => Array(
         [index - id] => 12[title] => Example Title[description] => Example Description
      )[1] => Array(
         [index - id] => 32[title] => Example Title[description] => Example Description
      )
   )

i want to take index-id to main array key my array must be like this

Array
   (
      [12] => Array(
         [index - id] => 12[title] => Example Title[description] => Example Description
      )[32] => Array(
         [index - id] => 32[title] => Example Title[description] => Example Description
      )
   )
load more v
22%

next($array) - advances the internal array pointer one place forward and returns its value,prev($array) - rewinds back the internal array pointer one place and returns the value of that element,If you want to get only the values of the array, you can use:   foreach ($array as $value).   It will ignore the key portion. If you want to get only the keys of the array, you can use:   foreach(array_keys($a) as $key),A multidimensional array is an array that has a value of an element as another array. Each element in the main array can also be an array. And each element in the sub-array can be an array.

Syntax
$arr[index1] = array(key1 => value1, key2 => value2);
$arr[index2] = array(key1 => value1, key2 => value2);
...
Example
< ? php
$life[] = 'nature';
$life['fruits'] = array('apples', 'banana', 'apricots');
$life['vegetables'] = array('tomatoes', 'cabbage', 'pumpkin'); ?
>

Accessing a specific sub-array's element

$main_array[key_main_array][key_sub_array]
Example
<?php
// define a two-dimensional array
$life[] = 'nature';
$life['fruits'] = array('apples', 'banana', 'apricots');
$life['vegetables'] = array('tomatoes', 'cabbage', 'pumpkin');

// gets the value of first element of the 'fruits' sub-array
$fruit1 = $life['fruits'][0];
echo 'I like '. $fruit1;             // I like apples

// modifies the value of first element of the 'fruits' sub-array
$life['fruits'][0] = 'grapes';
echo '<br /> I like '. $life['fruits'][0];             // I like grapes

// adds one more item in the 'vegetables' sub-array
$life['vegetables'][] = 'onions';
echo '<br /> Now, the "vegetables" sub-array has '. count($life['vegetables']). ' elements';
?>

<?php
// define a two-dimensional array
$life[] = 'nature';
$life['fruits'] = array('apples', 'banana', 'apricots');
$life['vegetables'] = array('tomatoes', 'cabbage', 'pumpkin');

foreach ($life as $k => $v) {
  // if $v is an Array, appllies another foreach() loop to it, to get its elements
  if(is_array($v)) {
    foreach ($v as $key => $val) {
      echo '<br />'. $k. ' - '. $key. ' : '. $val;
    }
  }
  else echo '<br />'. $k. ' - '. $v;
}
?>
Example
<?php
$life[] = 'nature';
$life['fruits'] = array('apples', 'banana', 'apricots');
$life['vegetables'] = array('tomatoes', 'cabbage', 'pumpkin');

print_r($life);
echo '<hr />';
var_export($life);
?>
Example
< ? php
$code = array(10 => "Perl", 20 => "PHP", 21 => "Python", 30 => "JavaScript");
$curent = current($code);
echo " the current() function returned: $curent";
$nxt = next($code);
echo " the next() function returned: $nxt";
$nxt = next($code);
echo " the next() function returned: $nxt";
$prv = prev($code);
echo " the prev() function returned: $prv";
$last = end($code);
echo " the end() function returned: $last"; ?
>

< ? php
$lang = array(1 => 'HTML', 10 => 'PHP', 20 => 'JavaScript', 'site' => ' https://coursesweb.net');
sort($lang); // sorts the array

var_export($lang); // array ( 0 => 'HTML', 1 => 'JavaScript', 2 => 'PHP', 3 => ' https://coursesweb.net', )
?
>

< ? php
$lang = array(1 => 'HTML', 10 => 'PHP', 20 => 'JavaScript', 'site' => 'coursesweb.net');
rsort($lang); // sorts the array

var_export($lang); // array ( 0 => 'coursesweb.net', 1 => 'PHP', 2 => 'JavaScript', 3 => 'HTML', )
?
>
asort($array)
< ? php
$lang = array(1 => 'HTML', 10 => 'PHP', 20 => 'JavaScript', 'site' => 'coursesweb.net');
asort($lang); // sorts the array

var_export($lang); // array ( 1 => 'HTML', 20 => 'JavaScript', 10 => 'PHP', 'site' => 'coursesweb.net', )
?
>
arsort($array)
< ? php
$lang = array(1 => 'HTML', 10 => 'PHP', 20 => 'JavaScript', 'site' => ' https://coursesweb.net');
arsort($lang); // sorts the array

var_export($lang); // array ( 'site' => ' https://coursesweb.net', 10 => 'PHP', 20 => 'JavaScript', 1 => 'HTML', )
?
>
This is useful mainly for associative arrays.
< ? php
$lang = array(1 => 'HTML', 10 => 'PHP', 20 => 'JavaScript', 'site' => ' https://coursesweb.net');
ksort($lang); // sorts the array

var_export($lang); // array ( 'site' => ' https://coursesweb.net', 1 => 'HTML', 10 => 'PHP', 20 => 'JavaScript', )
?
>
This is useful mainly for associative arrays.
< ? php
$lang = array(1 => 'HTML', 10 => 'PHP', 20 => 'JavaScript', 'site' => 'coursesweb.net');
krsort($lang); // sorts the array

var_export($lang); // array ( 20 => 'JavaScript', 10 => 'PHP', 1 => 'HTML', 'site' => 'coursesweb.net', ) 
?
>
natsort($array)
< ? php
$lang = array(1 => 'HTML', 10 => 'PHP', 20 => 'JavaScript', 'site' => 'coursesweb.net');
natsort($lang); // sorts the array

var_export($lang); // array ( 1 => 'HTML', 20 => 'JavaScript', 10 => 'PHP', 'site' => 'coursesweb.net', )
?
>
natcasesort($array)
< ? php
$lang = array(1 => 'HTML', 10 => 'PHP', 20 => 'JavaScript', 'site' => 'coursesweb.net');
natcasesort($lang); // sorts the array

var_export($lang); // array ( 1 => 'HTML', 20 => 'JavaScript', 10 => 'PHP', 'site' => 'coursesweb.net', )
?
>
shuffle($array)
< ? php
$lang = array(1 => 'HTML', 10 => 'PHP', 20 => 'JavaScript', 'site' => 'coursesweb.net');
shuffle($lang); // sorts the array

var_export($lang); // array ( 0 => 'PHP', 1 => 'coursesweb.net', 2 => 'HTML', 3 => 'JavaScript', )
?
>
array_keys($array)
< ? php
$lang = array(1 => 'HTML', 10 => 'PHP', 20 => 'JavaScript', 'site' => 'coursesweb.net');
$keys = array_keys($lang); // gets the keys

var_export($keys); // array ( 0 => 1, 1 => 10, 2 => 20, 3 => 'site', )
?
>
array_merge($array1, $array2, $array3)
< ? php
$lang = array(1 => 'HTML', 10 => 'PHP', 20 => 'JavaScript', 'site' => 'coursesweb.net');
$lang2 = array('ActionScript', 'Ruby');
$lang_merge = array_merge($lang, $lang2); // merge $lang and $lang2

var_export($lang_merge); // array ( 0 => 'HTML', 1 => 'PHP', 2 => 'JavaScript', 'site' => 'coursesweb.net', 3 => 'ActionScript', 4 => 'Ruby', )
?
>
array_sum($array)
< ? php
$nums = array(1, 7, 8, 25, 33, 78);
$nums_sum = array_sum($nums); // gets the sum

echo $nums_sum; // 152
?
>
in_array($val, $array)
< ? php
$lang = array(1 => 'HTML', 10 => 'PHP', 20 => 'JavaScript', 'site' => 'coursesweb.net');
$val = 'PHP';

if (in_array($val, $lang)) echo $val.
' is in $lang array'; // PHP is in $lang array
?
>
unset($array[key])
< ? php
$lang = array(1 => 'HTML', 10 => 'PHP', 20 => 'JavaScript', 'site' => 'coursesweb.net');
unset($lang['site']); // sorts the array

var_export($lang); // array ( 1 => 'HTML', 10 => 'PHP', 20 => 'JavaScript', )
?
>
implode(delimiter, $array)
< ? php
$lang = array(1 => 'HTML', 10 => 'PHP', 20 => 'JavaScript', 'site' => ' https://coursesweb.net');
$str_lang = implode(' | ', $lang); // sorts the array

echo $str_lang; // HTML | PHP | JavaScript | https://coursesweb.net
?
>
load more v
60%

This post will discuss several methods to get a subarray of a non-primitive array between specified indices in Java.,That’s all about getting a subarray of an array between specified indexes in Java.,Apache Commons ArrayUtils class provides subarray() method that returns an Object subarray containing the elements between specified indices. See how to convert an object array to an Integer array.,System.arraycopy() method can also be used to get a copy from the specified position in the source array to the specified position of the destination array.

load more v
48%

I want to get an array composed of the first 4 rows of the original array $arr,,You need to use array_slice().,Get answers to millions of questions and give back by sharing your knowledge with others.,If you find copyright violations, you can contact us at info-generacodice.com to request the removal of the content.

$subArray = array_slice($arr, 0, 4);
load more v

Other "array-undefined" queries related to "How to get sub array in PHP?"