PHP Store Key Value from Associative Array into Simple Array - php

I'm having trouble wrapping my head around this, any help would be GREAT...
I have an array $stores that is structured like so:
Array
(
[0] => Array
(
[id] => 123
[name] => 'Store A'
)
[1] => Array
(
[id] => 345
[name] => 'Store B'
)
[2] => Array
(
[id] => 567
[name] => 'Store C'
)
[3] => Array
(
[id] => 789
[name] => 'Store D'
)
)
I want to extract the 'id' values from this array into a simple array that looks this:
$simple = array(123,345,567,789);

If you use php 5.5+, array_column() is quite useful :
$simple = array_column($yourarray,'id');
http://php.net/array_column

Calimero definitely had the best answer for PHP 5.5+, but if you want the same functionality in prior versions, check this repository: https://github.com/ramsey/array_column . It is written by PHP 5.5 array_column creator itself.

If you can't use array_column, you can use array_map:
$names = array(
array('id' => 123, 'name' => 'A'),
array('id' => 456, 'name' => 'B'),
array('id' => 789, 'name' => 'C'),
);
$ids = array_map(function ($name) {
return $name['id'];
}, $names);
var_dump($ids);
// output
array(3) {
[0] => int(123)
[1] => int(456)
[2] => int(789)
}

You can simply use the following syntax if you are unable to upgrade the php version. In that kind of case use if (!function_exists('array_column')) to prevent re-declaration of the function which may occur on version upgrade.
Description From php.net
array_column() returns the values from a single column of the array, identified by the column_key. Optionally, you may provide an index_key to index the values in the returned array by the values from the index_key column in the input array.
/* Function array_column equivalent to php's array_column */
if (!function_exists('array_column'))
{
function array_column(array $array, $column_key, $index_key = NULL)
{
if (isset($array))
{
$return = array();
foreach ($array as $a)
{
if ($index_key)
{
if (!isset($a[$index_key]))
{
return array();
}
else
{
$return[$a[$index_key]] = $a[$column_key];
}
}
else
{
$return[] = $a[$column_key];
}
}
return $return;
}
return array();
}
}
Here are some examples taken from PHP.NET
<?php
$records = array(
array(
'id' => 2135,
'first_name' => 'John',
'last_name' => 'Doe',
),
array(
'id' => 3245,
'first_name' => 'Sally',
'last_name' => 'Smith',
),
array(
'id' => 5342,
'first_name' => 'Jane',
'last_name' => 'Jones',
),
array(
'id' => 5623,
'first_name' => 'Peter',
'last_name' => 'Doe',
)
);
$first_names = array_column($records, 'first_name');
print_r($first_names);
?>
It will give below output:
Array
(
[0] => John
[1] => Sally
[2] => Jane
[3] => Peter
)
Get column of last names from recordset, indexed by the "id" column
<?php
$last_names = array_column($records, 'last_name', 'id');
print_r($last_names);
?>
It will give you output as below:
Array
(
[2135] => Doe
[3245] => Smith
[5342] => Jones
[5623] => Doe
)

$simple = [];
foreach ($stores as $store){
$simple[] = $store['id'];
}

Related

How to print a array specific value from multidimensional arrays in php

Below is my array which i have printed:-
I want only the product_image from the array in loop
Array
(
[0] => Array
(
[product_option_id] => 247
[product_id] => 66
[product_option_value] => Array
(
[0] => Array
(
[product_option_value_id] => 42
[color_product_id] => 54
[name] => Pink
[product_image] => catalog/demo/teddy/03.jpg
[image] => http://192.168.15.9/Kids_stores/image/cache/catalog/axalta-ral-3015-light-pink-polyester-30-matt-powder-coating-20kg-box--1447-p-50x50.jpg
[price] =>
[price_prefix] => +
)
[1] => Array
(
[product_option_value_id] => 41
[color_product_id] => 67
[name] => Light Brown
[product_image] => catalog/Teddies/12-Baby-teddy/05.jpg
[image] => http://192.168.15.9/Kids_stores/image/cache/catalog/option-color/light_brown-50x50.jpg
[price] =>
[price_prefix] => +
)
[2] => Array
(
[product_option_value_id] => 43
[color_product_id] => 68
[name] => Cream
[product_image] => catalog/Teddies/12-Baby-teddy/11.jpg
[image] => http://192.168.15.9/Kids_stores/image/cache/catalog/option-color/cream-images-50x50.jpg
[price] =>
[price_prefix] => +
)
)
[option_id] => 5
[name] => COLOR
[type] => image
[value] =>
[required] => 0
)
)
Try this,
foreach($array as $val)
{
echo $val['product_image'];
}
Solution for your edited input:-
$image_array = array();
foreach ($your_array as $arr){
$image_array[] = array_column($arr['product_option_value'],'product_image');
}
Output:- https://eval.in/657966
You can take the array array_column and make it like this
$records = array (
array (
// your array
)
);
$variable = array_column($records, 'image');
echo $variable;
<?php $samples=$data['options'][0][product_option_value];
$product_image = array_column($samples, 'product_image');
echo'<pre>'; print_r($product_image );
?>
foreach($array as $key => $val){
if($key == 'product_image'){
echo "<img src='".$val."' />";
}
}
Try
You have to foreach the inner array:
foreach($array[product_option_value] as $val)
{
echo $val['product_image'];
}
Solution One:
<?php
$req_image=array();
$req_image[] = array_column($resultant_array, 'product_image');
print_r($req_image); // This will print all the images that are grouped under the array().
?>
Example:
The below is the PHP code and the sample output that you can obtain using the array_column().
PHP:
<?php
$records = array(
array(
'id' => 2135,
'first_name' => 'John',
'last_name' => 'Doe'
),
array(
'id' => 3245,
'first_name' => 'Sally',
'last_name' => 'Smith'
),
array(
'id' => 5342,
'first_name' => 'Jane',
'last_name' => 'Jones'
),
array(
'id' => 5623,
'first_name' => 'Peter',
'last_name' => 'Doe'
)
);
$lastNames = array_column($records, 'last_name', 'id');
Output:
If we call print_r() on $lastNames, you’ll see a resulting array that looks a bit like this:
Array
(
[2135] => Doe
[3245] => Smith
[5342] => Jones
[5623] => Doe
)
Solution Two: (As per requirement at last)
You can iterate the single key value alone in the foreach so that you can get the required parameter that you need.
foreach($resultant_array as $single_array)
{
foreach($single_array['product_option_value'] as $inner_array)
{
echo $inner_array['product_image']; // This will print the u=mage name that you need.
}
}
If you want one specified key and want minimal assumptions about array structure shoud use array_walk_recursive like this
$result = [];
array_walk_recursive($input,function ($value,$key) use (&$result) {
if ( 'product_image' == $key) {
$result[] = $value;
}
});

How to merge two nested associative array with same indexes? [duplicate]

This question already has answers here:
Merge row data from multiple arrays
(6 answers)
Closed 4 months ago.
I have two arrays with same indexes, and unfortunately array_merge_recursive doesn't work for me.
First array is like this:
$firstarray = array(
0 => array('id' => 1, 'name' => 'John Smith'),
1 => array('id' => 2, 'name' => 'Jane Doe')
);
Where second array is:
$secondarray = array(
0 => array('email' => 'john#smith.com'),
1 => array('email' => 'jane#doe.com')
);
Desired output would be like this,
Array
(
[0] => Array
(
[id] => 1
[name] => John Smith
[email] => john#smith.com
)
[1] => Array
(
[id] => 2
[name] => Jane Doe
[email] => jane#doe.com
)
)
But I am getting second array items appended to original array like this:
Array
(
[0] => Array
(
[id] => 1
[name] => John Smith
)
[1] => Array
(
[id] => 2
[name] => Jane Doe
)
[2] => Array
(
[email] => john#smith.com
)
[3] => Array
(
[email] => jane#doe.com
)
)
for($i = 0; $i<count($firstarray); $i++){
$output[] = array_merge($firstarray[$i],$secondarray[$i]);
}
You can the above mentioned code or you can use array_map() & array_merge().
Like:
$output = array_map('array_merge', $firstarray, $secondarray);
You guys sure go the complicated way :)
$mergedarray = array_map('array_merge', $firstarray, $secondarray);
Basically "merge the arrays of each index".
array_merge_recursive doesn't work because number index are not considered as associative key. So it just push the value instead of merging them.
Try this:
$firstarray = array(
0 => array('id' => 1, 'name' => 'John Smith'),
1 => array('id' => 2, 'name' => 'Jane Doe')
);
$secondarray = array(
0 => array('email' => 'john#smith.com'),
1 => array('email' => 'jane#doe.com')
);
foreach($firstarray as $key1 => $value1)
{
foreach($secondarray as $key2 => $value2)
{
if($key1 == $key2)
{
$firstarray[$key1]["email"] = $value2["email"];
}
}
}
print_r($firstarray);
Try below code:-
$firstarray = array(
0 => array('id' => 1, 'name' => 'John Smith'),
1 => array('id' => 2, 'name' => 'Jane Doe')
);
$secondarray = array(
0 => array('email' => 'john#smith.com'),
1 => array('email' => 'jane#doe.com')
);
Use simple foreach loop
$res = [];
foreach($firstarray as $k=>$record){
$record['email'] = $secondarray[$k]['email'];
$res[] = $record;
}
echo '<pre>'; print_r($res);
OR use array_map() function
$res = array_map(function($a,$b){
return ['id'=>$a['id'],'name'=>$a['name'],'email'=>$b['email']];
},$firstarray,$secondarray);
echo '<pre>'; print_r($res);

PHP multidimensional array search with provided array column (using PHP5 array_column)

I need help with array search. The array example is:
$users=Array
(
0 => Array
(
'id' => 111,
'name' => 'Sandra Shush',
'sources' => '1234,678,780'
),
1 => Array
(
'id' => 112,
'name' => 'Stefanie Mcmohn',
'sources' => '32,99,85'
),
2 => Array
(
'id' => 113,,
'name' => 'Michael',
'sources' => '896,1213,1918'
),
3 => Array
(
'id' => 113,,
'name' => 'Michael',
'sources' => '72'
)
);
I need to extract the key from the provided array above, where the "sources" key matches the search string (integer).
I've tried with:
$key = array_search('99', array_column( $users, 'sources') ); // false
But of course, there's no chance to retrieve the key with this method. It only works if source key has only one value, for example:
$key = array_search('72', array_column( $users, 'sources') ); // 3
Is there a way to achieve this?
Thank you
Simply use foreach loop along with preg_match like as
$result = [];
foreach($users as $key => $value){
if(preg_match("/\b99\b/",$value['sources']) !== false){
$result[] = $key;
}
}
print_r($result);
Output:
Array
(
[0] => 1
)
Demo

Get column values from an associative array in php

I have an array of form:
$records = array(
array(
'id' => 2135,
'first_name' => 'John',
'last_name' => 'Doe',
),
array(
'id' => 3245,
'first_name' => 'Sally',
'last_name' => 'Smith',
),
array(
'id' => 5342,
'first_name' => 'Jane',
'last_name' => 'Jones',
),
array(
'id' => 5623,
'first_name' => 'Peter',
'last_name' => 'Doe',
)
);
I want output like this :
EDIT:
Array
( array('first_Name' => John),
array('first_Name'=> Sally),
array('first_Name'=> Jane),
array('first_Name'=> Peter)
);
Can this be achieved??
You cannot do this since you can't have duplicate keys in an array.
Here is a related question: How to allow duplicate keys in a PHP array?
This article explains how PHP stores array internally: http://nikic.github.io/2012/03/28/Understanding-PHPs-internal-array-implementation.html.
Answer after your edit:
$arr = array();
foreach($records as $value) {
$arr[] = array('first_name' => $value['first_name']);
}
print_r($arr);
You can achieve your (edited) question like this:
$new_array = array();
foreach($records as $record)
$new_array[] = array('first_Name'=>$records['first_name']);
try this
$records = array(
array(
'id' => 2135,
'first_name' => 'John',
'last_name' => 'Doe',
),
array(
'id' => 3245,
'first_name' => 'Sally',
'last_name' => 'Smith',
),
array(
'id' => 5342,
'first_name' => 'Jane',
'last_name' => 'Jones',
),
array(
'id' => 5623,
'first_name' => 'Peter',
'last_name' => 'Doe',
)
);
$tmp = array('first_name' => '');
foreach ($records as &$record) {
$record = array_intersect_key($record, $tmp);
// or $record = array('first_name' => $record['first_name']);
}
unset($record);
var_dump($records);
If you want to array with in the array means, surely it will generated with index key, like this
Array
( '0' => array('first_Name' => John),
'1' => array('first_Name'=> Sally),
'2' => array('first_Name'=> Jane),
'3' => array('first_Name'=> Peter)
);
Try this one,
foreach($records as $record) {
$name_array[] = Array('first_Name' =>$record['first_name']);
}
print_r($name_array);
Your output will be,
Array
(
[0] => Array
(
[first_Name] => John
)
[1] => Array
(
[first_Name] => Sally
)
[2] => Array
(
[first_Name] => Jane
)
[3] => Array
(
[first_Name] => Peter
)
)
To get your desired output you can use array_map, though you can get similar output with array_column which is new in PHP 5.5.
With array_map (http://3v4l.org/v8Y8Z):
<?php
$firstNames = array_map(function($record) {
return ['first_name' => $record['first_name']];
}, $records);
With array_column (http://3v4l.org/ohnGu):
$firstNames = array_column($records, 'first_name');
Note: array_column doesn't make subarrays with the first_name key.
you can try this one
$arr_output = array();
foreach($records as $key=>$arr)
{
$arr_output['id'][] = $arr['id'];
$arr_output['first_name'][] = $arr['first_name'];
$arr_output['last_name'][] = $arr['last_name'];
}
print_r($arr_output['first_name']); // display all first names
print_r($arr_output); // display complete output array.
Output :
Array
(
[id] => Array
(
[0] => 2135
[1] => 3245
[2] => 5342
[3] => 5623
)
[first_name] => Array
(
[0] => John
[1] => Sally
[2] => Jane
[3] => Peter
)
[last_name] => Array
(
[0] => Doe
[1] => Smith
[2] => Jones
[3] => Doe
)
)
Demo
This is not possible, because you cannot have multiple elements of the same key in an associative array.

Which PHP Array function should I use?

I have two arrays:
Array
(
[0] => Array
(
[id] => 1
[type] => field
[remote_name] => Title
[my_name] => title
[default_value] => http%3A%2F%2Ftest.com
)
[1] => Array
(
[id] => 2
[type] => field
[remote_name] => BookType
[my_name] => book-type
[default_value] =>
)
[2] => Array
(
[id] => 3
[type] => value
[remote_name] => dvd-disc
[my_name] => dvd
[default_value] =>
)
)
Array
(
[title] => Test
[book-type] => dvd
)
I need to take each key in the second array, match it with the my_name value in the first array and replace it with the corresponding remote_name value of the first array while preserving the value of the second array.
There's got to be some carrayzy function to help!
EDIT: There will also be a few cases that the value of the second array will need to be replaced by the value of the first array's remote_name where the value of the second array matches the value of the first array's my_name. How can I achieve this?
EG: book-type => dvd should turn into BookType => dvd-disc
Like so?:
$first = array(
array(
'id' => 1,
'type' => 'field',
'remote_name' => 'Title',
'my_name' => 'title',
'default_value' => 'http%3A%2F%2Ftest.com',
),
array(
'id' => 2,
'type' => 'field',
'remote_name' => 'BookType',
'my_name' => 'book-type',
'default_value' => '',
),
array(
'id' => 3,
'type' => 'value',
'remote_name' => 'dvd-disc',
'my_name' => 'dvd',
'default_value' => '',
),
);
$second = array(
'title' => 'Test',
'book-type' => 'dvd',
);
$map = array('fields' => array(), 'values' => array());
foreach ($first as $entry) {
switch ($entry['type']) {
case 'field':
$map['fields'][$entry['my_name']] = $entry['remote_name'];
break;
case 'value':
$map['values'][$entry['my_name']] = $entry['remote_name'];
break;
}
}
$new = array();
foreach ($second as $key => $val) {
$new[isset($map['fields'][$key]) ? $map['fields'][$key] : $key] = isset($map['values'][$val]) ? $map['values'][$val] : $val;
}
print_r($new);
Output:
Array
(
[Title] => Test
[BookType] => dvd-disc
)
Explanation:
The first loop collects the my_name/remote_name pairs for fields and values and makes them more accessible.
Like so:
Array
(
[fields] => Array
(
[title] => Title
[book-type] => BookType
)
[values] => Array
(
[dvd] => dvd-disc
)
)
The second loop will traverse $second and use the key/value pairs therein to populate $new. But while doing so will check for key/value duplicates in $map.
Keys or values not found in the map will be used as is.
foreach($arr1 as &$el) {
$el['remote_name'] = $arr2[$el['my_name']];
}
unset($el);
I am not aware of such a carrayzy function, but I know how you could do it:
//$array1 is first array, $array2 is second array
foreach($array1 as $key => $value){
if (isset($value['remote_name'], $value['my_name']) && $value['remote_name'] && $value['my_name']){
$my_name = $value['my_name'];
if (isset($array2[$my_name])) {
$remote_name = $value['remote_name'];
$array2[$remote_name] = $array2[$my_name];
//cleanup
unset($array2[$my_name]);
}
}
}

Categories