PHP : How to extract value of multidimensionnal array? - php

I have this multidimensional array and I would like to get from it only array('13', '11', '12', '10'). How can I get this?
array
0 =>
array
'id' => '13'
1 =>
array
'id' => '11'
2 =>
array
'id' => '12'
3 =>
array
'id' => '10'

for($i =0 ;$i<count($array);$i++)
{
echo $array[$i]['id'];
}

try
$values = array();
foreach($arr as $inner)
{
$values[] = $inner['id'];
}
// $values should now hold array(13, 11, 12, 10)

Try this :
$array = your array
$result = call_user_func_array('array_merge_recursive', $array);
echo "<pre>";
print_r($result['id']);

Try this :
<?php
$array=Array('0'=>Array('id'=>"1"),'1'=>Array('id'=>"2"),'2'=>Array('id'=>"3"),'4'=>Array('id'=>"4"));
$arr=Array();
for($i =0 ;$i<3;$i++)
{
$arr[$i]=$array[$i]['id'];
}
print_r(implode(',',$arr));
?>
O/p:
1,2,3

$values = array();
foreach(new \RecursiveIteratorIterator(new \RecursiveArrayIterator($arr)) as $key => $value) {
if ($key == 'id') $values[] = $value;
}
var_dump($values);

Related

PHP - How to check two arrays and search for matching keys and merge the values

How to check two arrays and search for matching keys and merge the values of the 1st array with the matching keys of the second array.Please help me as I'm new to this.
example :
1st array = {id => 11,name => 'name',age => 18 }
2nd array = {id,name,age,school}
I want to get the result by adding the matching values to the 2nd array
2nd array = {id => 11,name => 'name',age => 18,school => }
try this
$a = ['id' => 11,'name' => 'name','age' => 18];
$b = array_flip(['id','name','age','school']);
foreach($b as $key => &$value){
$value = '';
}
$result = array_merge($b, $a);
One of the simple way is looping
$first= array('id' => 11,'name' => 'name','age' => 18 );
$second = array('id','name','age','school');
foreach ($second as $value) {
if(isset($first[$value])){
$final[$value] = $first[$value];
}
};
print_r($final);
Second Array flip and array merge
$first = ['id' => 11,'name' => 'name','age' => 18];
$second= array_flip(['id','name','age','school']);
foreach($second as $key => s$value){
$value = '';
}
$result = array_merge($second, $first);
print_r($result);
Use array_merge
<?php
$array1 = array('id' => '11', 'name' => 'name', 'age' => 18);
$array2 = array('id','name','age','school');
$array3 = array_merge(array_fill_keys($array2, null), $array1);
print_r($array3);
?>

Compare keys and values from 2 arrays and store same values

I want to compare keys from one array against values from another array, and when a match is made to store the value from the first array (whose key matched the value in the second one).
With my code, it always echoes out 4. How can I modify it so that it echoes out 1 2 3 4?
The code:
$first = array('location', 'genre', 'studio', 'Lord_Of_the_Rings');
$second = array(
'location' => 1,
'genre' => 2,
'studio' => 3,
'Lord_Of_the_Rings' => 4
);
while ($el = current($second)) {
$d .= ','.key($second);
next($second);
}
$d = ltrim($d, ',');
$d = explode(',', $d);
foreach ($first as $the_tax) {
foreach ($d as $key => $v) {
if (in_array($v, $first)) {
$t = $second[$v];
}
}
echo $t.'<br>';
}
To be honsest, if you wouldn't explain your goal, I wouldn't even understand what you're trying to do by your code. Try like this:
<?php
$first = array('location', 'genre', 'studio', 'Lord_Of_the_Rings');
$second = array(
'location' => 1,
'genre' => 2,
'studio' => 3,
'Lord_Of_the_Rings' => 4
);
$intersect = array_intersect($first, array_keys($second));
foreach($intersect as $key)
echo $second[$key];
?>
You should move/add add an echo statement into the block where you assign the value of $t, maybe this way:
foreach ($first as $the_tax) {
foreach ($d as $key => $v) {
if (in_array($v, $first)) {
$t = $second[$v];
echo $t.' ';
}
}
echo '<br>';
}
you can flip the keys in second array, and then take the intersection of the 2. something along these lines
<?php
$first = array('location', 'genre', 'studio', 'Lord_Of_the_Rings');
$second = array(
'location' => 1,
'genre' => 2,
'studio' => 3,
'Lord_Of_the_Rings' => 4
);
$flipped = array_flip($second);
print implode(' ',array_keys(array_intersect($flipped, $first)));
?>

php array merge and convert to json

I have two arrays (below). Is it possible to convert them into json string?
Array
(
[0] => size
[1] => color
)
Array
(
[0] => L
[1] => Black
)
Output structure should be:
[
{"name":"size","value":"L"},
{"name":"color","value":"Black"}
]
Thanks!
Sure:
$array1 = array('size', 'color');
$array2 = array('L', 'Black');
$jsonArray = array();
foreach (array_combine( $array1, $array2 ) as $name => $value) {
$jsonArray[] = array('name' => $name, 'value' => $value);
}
echo $json = json_encode($jsonArray);
This gives you
[{"name":"size","value":"L"},{"name":"color","value":"Black"}]
this here should work:
$json = json_encode( array_combine( $array1, $array2 ) );
Something like this should work just how you want:
<?php
$keys = array("size", "color");
$values = array("L", "Black");
$array = array();
foreach ($keys as $i => $key) {
$array[] = array(
"name" => $key,
"value" => $values[$i]
);
}
$json = json_encode($array);
var_dump($json);
//string(62) "[{"name":"size","value":"L"},{"name":"color","value":"Black"}]"
?>
$array1 = array('size', 'color');
$array2 = array('L', 'Black');
$result = array_combine($array1 , $array2);
$json = array();
foreach($result as $key => $val){
$json[] = array('name' => $key, 'value' => $value);
}
$json = json_encode($json);
I think you are looking for this:
$array1 = array('size', 'color');
$array2 = array('L', 'Black');
for($i=0;$i<sizeof($array1);$i++)
{
$array3[]=array($array1[$i]=>$array2[$i]);
}
echo json_encode($array3);
?>
Output:
[{"size":"L"},{"color":"Black"}]

Combining two arrays by ID in PHP [duplicate]

This question already has answers here:
Merge two indexed arrays of indexed arrays based on first column value
(2 answers)
Closed 5 months ago.
I need to compare two 2D arrays in PHP. The arrays look like this:
Array one
ID Name
11 Aa
11 Ab
12 Bb
13 Cc
14 Dd
15 Ee
Array two
ID Content
11 Cat
13 Dog
14 Donkey
Now I'd need to combine these two into an array like this:
ID Name Conent
11 Aa Cat
11 Ab Cat
12 Bb
13 Cc Dog
14 Dd Donkey
15 Ee
How can I accomplish this? I have had no luck with array_merge() or $array3 = $array1 + $array2;
A quick way would be to iterate over the first array and append the value from the second:
$array1 = array('11' => 'Aa', '12' => 'Bb', '13' => 'Cc', '14' => 'Dd', '15' => 'Ee');
$array2 = array('11' => 'Cat', '13' => 'Dog', '14' => 'Donkey');
$combined = array();
foreach ($array1 as $key => $val) {
$combined[$key] = $val . (isset($array2[$key]) ? ' '.$array2[$key] : '');
}
This will loop through every key/value in $array1 and add it to the $combined array. If a value in $array2 exists with the same index, it will append it to that value from $array1, separated with a space.
UPDATE: I misread the format of the arrays (again). I assumed ID was the actual index in the array, but as the example array output has both Name and Content, I'm assuming ID is an actual index string value and not the index in the array itself. To stick with the loop scenario, you can iterate through the first array and have a nested loop iterate through the second:
$array1 = array(
array('ID' => '11', 'Name' => 'Aa'),
array('ID' => '12', 'Name' => 'Bb'),
array('ID' => '13', 'Name' => 'Cc'),
array('ID' => '14', 'Name' => 'Dd'),
array('ID' => '15', 'Name' => 'Ee'),
);
$array2 = array(
array('ID' => '11', 'Content' => 'Cat'),
array('ID' => '13', 'Content' => 'Dog'),
array('ID' => '14', 'Content' => 'Donkey')
);
$combined = array();
foreach ($array1 as $arr) {
$comb = array('ID' => $arr['ID'], 'Name' => $arr['Name'], 'Content' => '');
foreach ($array2 as $arr2) {
if ($arr2['ID'] == $arr['ID']) {
$comb['Content'] = $arr2['Content'];
break;
}
}
$combined[] = $comb;
}
This will add every value in $array1 to the combined array and if, and only if, a value in $array2 contains the same ID field will it add it's Content field to the array too. This can be extended to handle any number of fields as well, either by name, or by changing the inner-if block to have $comb += $arr2; instead (which should merge all non-existing indexes).
You will have to make your own function:
function putThemTogether($array1, $array2) {
$output = array();
foreach($array1 as $key => $value) {
if (!isset($output[$key]))
$output[$key] = array();
$output[$key][] = $value;
}
foreach($array2 as $key => $value) {
if (!isset($output[$key]))
$output[$key] = array();
$output[$key][] = $value;
}
return $output;
}
To make this better you could make it take an arbitrary number of arguments.
$result = array_map (
function ($item) { return is_array($item) ? implode(' ', $item) : $item; },
array_merge_recursive($array1, $array2);
);
Note, that both arrays require string keys
Another solution for this is to use array_search and array_column (since PHP 5.5.0).
foreach ($array1 as $key => $val) {
$found_key = array_search($val['ID'], array_column($array2, 'ID'));
if ($found_key !== false) { $array1[$key]['Content'] = $array2[$found_key]['Content']; }
}
Try this I hope It'll work
function merge_two_arrays($array1,$array2) {
$data = array();
$arrayAB = array_merge($array1,$array2);
foreach ($arrayAB as $value) {
// This assumes there is a field called "id"
$id = $value['id'];
if (!isset($data[$id])) {
$data[$id] = array();
}
$data[$id] = array_merge($data[$id],$value);
}
return $data;
}
$master_array = merge_two_arrays($array1,$array2);

shift all array elements up one level in a multidimensional array

I have an array that may look like
$arr = array(
array(
'test1' => 'testing1'
),
array(
'test2' => array(
1 =>'testing2
)
);
and I want to turn it into
$newArr = array(
'test1' => 'testing1',
'test2' => array(
1 => 'testing2'
)
);
so i have been trying to shift all array elements up one level.
eidt:
this is my method that combines 2 array together:
public function arrayMerge($arr1, $arr2)
{
foreach($arr2 as $key => $value) {
$condition = (array_key_exists($key, $arr1) && is_array($value));
$arr1[$key] = ($condition ? $this->arrayMerge($arr1[$key], $arr2[$key]) : $value);
}
return $arr1;
}
It's somewhat trivial, many ways are possible.
For example using the array union operator (+)­Docs creating the union of all arrays inside the array:
$newArr = array();
foreach ($arr as $subarray)
$newArr += $subarray;
Or by using array_merge­Docs with all subarrays at once via call_user_func_array­Docs:
$newArray = call_user_func_array('array_merge', $arr);
Try
$arr = array(
array('test1' => 'testing1' ),
array('test2' => array(1 =>'testing2'))
);
$new = array();
foreach($arr as $value) {
$new += $value;
}
var_dump($new);
Output
array
'test1' => string 'testing1' (length=8)
'test2' =>
array
1 => string 'testing2' (length=8)

Categories