How can I merge array's items? - php

I have an array like this:
$arr = array ( [0] => array("red","green"),
[1] => array("blue","yellow")
);
And this is expected result:
Array ( [0] => red [1] => green [2] => blue [3] => yellow )
See? I want to merge all items of $arr (which are also array themselves). How can I do that?
I can do a loop on it and then use array_merge() every time like this:
$res = [];
foreach ( $arr as $item ) {
$res = array_merge($res, $item);
}
It works as well. But I guess I can write it better. Any idea?

You can do trick with call_user_func_array:
$result = call_user_func_array('array_merge', $arr);
This trick is possible, because array_merge accept dynamic arguments count.

It's a style exercise, but if the structure remains the same as in your example, you can play with this:
$arr = array ( '0' => array("red","green"),
'1' => array("blue","yellow")
);
$res = explode(",",str_replace(array('[',']'),'',json_encode($arr)));
Hope this helps.

You declare array in wrong way:
$arr = array ( 0 => array("red","green"),
1 => array("blue","yellow")
);
The error reported by PHP says it clearly:
Fatal error: Illegal offset type in /in/Hhfqa on line 3
Line 3 in your example is exactly line of first array element.
Please check http://php.net/manual/en/language.types.array.php

Related

reconstruct an array to remove a parent in PHP

i want to restructure my array so that it looks better in a json
here is a print_r of my current variable:
Array
(
[0] => Array
(
[item_id] => 2
)
[1] => Array
(
[item_id] => 1
)
[2] => Array
(
[item_id] => 1
)
)
i want to reconstruct it be like this or similar:
EDIT
Array
(
[item_id] = array([0]=>'2',[1]=>'1', [2]=>'1');
)
sorry for my poor english m(_ _)m
i just want the item_id to have multiple values.
The hurdle
You actually can't in any way produce the output that you desire, since the key needs to be unique.
You can't use a key of item_id more than once, every time you try and set it, it will override what was in there last.
Think about it, how do you then look up the item with key of item_id, you can't, because three things would have that same key.
If the only reason is for cosmetics, I'd leave the output as you currently have it, although it may look a little messy in your JSON, it works.
A different approach
The best you can hope, is to get an output of:
'item_id' => array(
2,
1,
1
)
You can do this with the help of the array_map function:
$array = array('item_id' => array_map('current', $array));
This can be accomplished using this code.
$a['item_id'] = array();
foreach($arr as $key=>$val) {
$a['item_id'][] = $val['item_id'];
}
print_r($a);
$array = array('item_id' => array_map('current', $array));

PHP extract array values with the same key into another array

I have an array as so:
$diff_date_results =
Array (
[0] => Array ( [differential] => 7.7 [date] => 2012-12-30 )
[1] => Array ( [differential] => 8.2 [date] => 2012-12-31 )
[2] => Array ( [differential] => 9.9 [date] => 2013-01-03 )
)
I would like to extract all values from the differential key of each of the inner arrays to use the array_sum function on the newly created array.
I have this, which draws out the three numbers for me, but I get php errors for each number as an undefined index. (Notice: Undefined index: 7.7 in C:\wamp\www\jquery\test.php on line 55)
My code thus far is as follows:
$diff_results = array();
foreach($diff_date_results as $entry){
$diff_results[$entry['differential']];
}
print_r($diff_results);
I am sure it is simple, I have been screwing around with it for way too long now, any help would be wonderful!
Thanks.
$diff_results = array();
foreach($diff_date_results as $entry){
$diff_results[] = $entry['differential'];
}
//just for displaying all differential
print_r($diff_results);
Now, you can use array_sum on $diff_results.
Moreover, if you want to have sum then you can use below method too.
$diff_results = "";
foreach($diff_date_results as $entry){
$diff_results = $diff_results + $entry['differential'];
}
//$diff_results will have sum of all differential
echo $diff_results;
$diff_results = array_map($diff_date_results,
function($entry) { return $entry['differential']; });
Do it like this:
$diff_results = array();
foreach($diff_date_results as $key => $entry){
$diff_results[] .= $entry['differential']];
}
print_r($diff_results);
Thanks.
$diff_date_results = array (
0 => array ( 'differential'=> 7.7, 'date' => 20),
1 => Array ( 'differential' => 8.8, 'date' => 20 ),
2 => Array ( 'differential' => 9.8 ,'date' => 20 ),
);
$value_differential=array();
foreach( $diff_date_results as $key=>$value){
print_r($value);
$value_differential[]=$value['differential'];
}
print_r(array_sum($value_differential));
For anyone stumbling across this question as I have, the best solution in my opinion is a working version of Barmars as below:
$diff_results = array_map(function($entry)
{
return $entry['differential'];
},
$diff_date_results);
it's a more elegant, 1 line solution (which I've expand to 5 lines for readability).

PHP rewriting a json array (Undefined offset)

I'm taking some json, made by OpenLibrary.org, and remake a new array from the info.
Link to the OpenLibrary json
here is my PHP code to decode the json:
$barcode = "9781599953540";
function parseInfo($barcode) {
$url = "http://openlibrary.org/api/books?bibkeys=ISBN:" . $barcode . "&jscmd=data&format=json";
$contents = file_get_contents($url);
$json = json_decode($contents, true);
return $json;
}
the new array I'm trying to make looks something like this:
$newJsonArray = array($barcode, $isbn13, $isbn10, $openLibrary, $title, $subTitle, $publishData, $pagination, $author0, $author1, $author2, $author3, $imageLarge, $imageMedium, $imageSmall);
but when I try to get the ISBN_13 to save it to $isbn13, I get an error:
Notice: Undefined offset: 0 in ... on line 38
// Line 38
$isbn13 = $array[0]['identifiers']['isbn_13'];
And even if I try $array[1] ,[2], [3].... I get the same thing. What am I doning wrong here! O I know my Valuable names might not be the same, that's because they are in different functions.
Thanks for your help.
Your array is not indexed by integers, it is indexed by ISBN numbers:
Array
(
// This is the first level of array key!
[ISBN:9781599953540] => Array
(
[publishers] => Array
(
[0] => Array
(
[name] => Center Street
)
)
[pagination] => 376 p.
[subtitle] => the books of mortals
[title] => Forbidden
[url] => http://openlibrary.org/books/OL24997280M/Forbidden
[identifiers] => Array
(
[isbn_13] => Array
(
[0] => 9781599953540
)
[openlibrary] => Array
(
[0] => OL24997280M
)
So, you need to call it by the first ISBN, and the key isbn_13 is itself an array which you must access by element:
// Gets the first isbn_13 for this item:
$isbn13 = $array['ISBN:9781599953540']['identifiers']['isbn_13'][0];
Or if you need a loop over many of them:
foreach ($array as $isbn => $values) {
$current_isbn13 = $values['identifiers']['isbn_13'][0];
}
If you expect only one each time and must be able to get its key without knowing it ahead of time but don't want a loop, you can use array_keys():
// Get all ISBN keys:
$isbn_keys = array_keys($array);
// Pull the first one:
$your_item = $isbn_keys[0];
// And use it as your index to $array
$isbn13 = $array[$your_item]['identifiers']['isbn_13'][0];
If you have PHP 5.4, you can skip a step via array dereferencing!:
// PHP >= 5.4 only
$your_item = array_keys($array)[0];
$isbn13 = $array[$your_item]['identifiers']['isbn_13'][0];

checking to see if a vaule is in a particular key of an array

I'm new to working with arrays so I need some help. With getting just one vaule from an array. I have an original array that looks like this:
$array1= Array(
[0] => 1_31
[1] => 1_65
[2] => 29_885...)
What I'm trying to do is seach for and return just the value after the underscore. I've figured out how to get that data into a second array and return the vaules as a new array.
foreach($array1 as $key => $value){
$id = explode('_',$value);
}
which gives me:
Array ( [0] => 1 [1] => 31 )
Array ( [0] => 1 [1] => 65 )
Array ( [0] => 29 [1] => 885 )
I can also get a list of the id's or part after the underscore by using $id[1] I'm just not sure if this is the best way and if it is how to do a search. I've tried using in_array() but that searches the whole array and I couldn't make it just search one key of the array.
Any help would be great.
If the part after underscore is unique, make it a key for new array:
$newArray = array();
foreach($array1 as $key => $value){
list($v,$k) = explode('_',$value);
$newArray[$k] = $v;
}
So you can check for key existence with isset($newArray[$mykey]), which will be more efficient.
You can use preg_grep() to grep an array:
$array1= array("1_31", "1_65", "29_885");
$num = 65;
print_r(preg_grep("/^\d+_$num$/", $array1));
Outputs:
Array
(
[1] => 1_65
)
See http://ideone.com/3Fgr8
I would say you're doing it just about as well as anyone else would.
EDIT
Alternate method:
$array1 = array_map(create_function('$a','$_ = explode("_",$a); return $_[1];'),$array1);
echo in_array(3,$array1) ? "yes" : "no"; // 3 being the example
I would have to agree. If you wish to see is a value exists in an array however just use the 'array_key_exists' function, if it returns true use the value for whatever.

Grouping array values in php

I have an array with some value like this:
[Organization_id] => Array
(
[0] => 4
[1] => 4
[2] => 4
)
but i want some thing like this:
[Organization_id] => Array
(
[0] => 4
)
Thanks in advance..
If you don't care about the key to value association possibly messing up, you can use this:
$array = array_unique($array);
Although array_unique was mentioned twice now, I feel the answers failed to point out that you have to use the function on the nested array and not the array itself, so here is a usage example
$array = array( 'Organization_id' => array(4,4,4) );
$array['Organization_id'] = array_unique( $array['Organization_id'] );
print_r($array);
which will do what you want.

Categories