How to create key from the array value? - php

I have an array that contains two values, but i need upper value as key of lower value like value of name replace with value and also remove name from array.
Array
(
[0] => Array
(
[name] => firt_name
[value] => Robin
)
[1] => Array
(
[name] => last_name
[value] => Singh
)
[2] => Array
(
[name] => email
[value] => 123#gmail.com
)
[3] => Array
(
[name] => password
[value] => 12345
)
)
Here is the code
function key_replace($params = array())
{
if (!empty($params)) {
$array[] = array();
foreach ($params as $key => $value) {
$array[$value['name']] = $value['value'];
}
print_r($array);
}
}
Any solution appreciated!

Another approach is to use array_column and array_combine
array_combine(array_column($array, 'name'), array_column($array, 'value'));
https://3v4l.org/boAOI

A Simple foreach() will do the trick for you.
$result = [];
foreach($array as $k=>$v){
$result[$v['name']] = $v['value'];
}
print_r($result);
WORKING DEMO: https://3v4l.org/hH39i

$datas = $array = array
(
'0' => array
(
'name' => 'firt_name',
'value' => 'Robin'
)
,
'1' => array
(
'name' => 'last_name',
'value' => 'Singh'
)
,
'2' => array
(
'name' => 'email',
'value' => '123#gmail.com'
)
,
'3' => array
(
'name' => 'password',
'value' => '12345',
)
,
'4' => array
(
'name' => 'phone',
'value' => 'skdsjdkdjskd'
)
,
'5' => Array
(
'name' => 'city',
'value' => 'dskjdksjd'
)
,
'6' => Array
(
'name' => 'state',
'value' => 'kjksdjskdsk'
)
);
$array = '';
foreach ($datas as $key => $value) {
$array[$value['name']] = $value['value'];
}
echo '<pre>';
print_r($array);
echo '</pre>';
Array
(
[firt_name] => Robin
[last_name] => Singh
[email] => 123#gmail.com
[password] => 12345
[phone] => skdsjdkdjskd
[city] => dskjdksjd
[state] => kjksdjskdsk
)

Related

PHP - MySql Query result format change [duplicate]

This is my db result,
Array ([0] => Array ( [shopname] => Shop name [fueltype] => Pertol [amount] => 1000 )
[1] => Array ( [shopname] => dfsdfsd [fueltype] => Pertol [amount] => 54456 )
[2] => Array ( [shopname] => dfsdfsd [fueltype] => Disel [amount] => 54456 )
)
I need result like
[["Shop name", "Pertol", 1000],["dfsdfsd", "Pertol", 54456],["Shop name", "Disel", 54456]]
How to get like this, I have no idea?
array_map() along with array_values() will work for you:-
<?php
$array = Array ( '0' => Array ( 'shopname' => 'Shop name','fueltype' => 'Pertol','amount' => 1000 ),
'1' => Array ( 'shopname' => 'dfsdfsd' ,'fueltype' => 'Pertol','amount' => 54456 ),
'2' => Array ( 'shopname' => 'dfsdfsd','fueltype' => 'Disel','amount' => 54456 )
);
$values_data_only = array_map('array_values', $array);
$desire_result = json_encode($values_data_only);
echo $desire_result;
?>
Output:- https://eval.in/395344
Also via simple foreach() it is possible:-
<?php
$array = Array ( '0' => Array ( 'shopname' => 'Shop name','fueltype' => 'Pertol','amount' => 1000 ),
'1' => Array ( 'shopname' => 'dfsdfsd' ,'fueltype' => 'Pertol','amount' => 54456 ),
'2' => Array ( 'shopname' => 'dfsdfsd','fueltype' => 'Disel','amount' => 54456 )
);
$new_array = array();
foreach ($array as $k=> $arr){
$new_array[$k][] = $arr['shopname'];
$new_array[$k][] = $arr['fueltype'];
$new_array[$k][] = $arr['amount'];
}
echo "<pre/>";print_r($new_array);
$desired_result_2 = json_encode($new_array);
echo $desired_result_2;
?>
Output:-https://eval.in/395354
$mapped = array_map('array_values', $input_array); // apply filter so we dont get the keys
$json = json_encode($mapped);
Just try with:
$input = array( /* your input data */ );
$output = array();
foreach ($input as $data) {
$output[] = array_values($data);
}

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;
}
});

Merge and group rows from multiple 2d arrays based on a shared column value then push another column's data into subarrays

Scenario:
I have these 2 arrays:
array1:
Array
(
[1] => Array
(
[label] => pending
[fillColor] => #468847
[data] => 50
)
[2] => Array
(
[label] => dispatched
[fillColor] => #6ecf70
[data] => 10
)
[3] => Array
(
[label] => delivered
[fillColor] => #f89406
[data] => 1
)
[4] => Array
(
[label] => invoiced
[fillColor] => #3a87ad
[data] => 2
)
)
array2:
Array
(
[1] => Array
(
[label] => pending
[fillColor] => #468847
[data] => Array
(
[0] => 1
)
)
)
The result I need is
Array
(
[1] => Array
(
[label] => pending
[fillColor] => #468847
[data] => Array
(
[0] => 50
[1] => 1
)
)
[2] => Array
(
[label] => dispatched
[fillColor] => #6ecf70
[data] => Array
(
[0] => 10
[1] => 0
)
)
[3] => Array
(
[label] => delivered
[fillColor] => #f89406
[data] => Array
(
[0] => 1
[1] => 0
)
)
[4] => Array
(
[label] => invoiced
[fillColor] => #3a87ad
[data] => Array
(
[0] => 2
[1] => 0
)
)
)
There are only 4 labels:
pending
dispatched
delivered
invoiced
Please note that the arrays are just an example. It can happen that the first array has no values at all or just 2 and the second array have 3 values or none.
Because of that constraint above I'm thinking to use array_replace and having an array called
base_array = ["pending", "dispatched", "delivered", "invoiced"]
I have tried to loop the base_array and try to match the array1 with array2 if label exist.
Basically, if key (which is label) is not exist in any of array1 or array2 then the value replaced will be 0 in the resulting array.
I have tried
foreach($base_array as $key => $value) {
if(in_array($key, $array1[$key])) {
$array[$key] = $array1[$key];
}
}
but it looks like I'm lost on these multi dimensional arrays and replacing. Any help will be really appreciated. Thanks.
From what i understand from your question you can do it like this :-
$array = array(
'1' => Array
(
'label' => 'pending',
'fillColor' => '#468847',
'data' => '50'
),
'2' => Array
(
'label' => 'dispatched',
'fillColor' => '#6ecf70',
'data' => '10'
),
'3 ' => Array
(
'label' => 'delivered',
'fillColor' => '#f89406',
'data' => '1'
),
'4' => Array
(
'label' => 'invoiced',
'fillColor' => '#3a87ad',
'data' => '2'
),
);
$array2 = array
(
'1' => Array
(
'label' => 'pending',
'fillColor' => '#468847',
'data' => array
(
'0' => '1'
)
)
);
$temp = array();
$i = 0;
foreach ($array as $key => $value) {
$temp[$key]['label'] = $value['label'];
$temp[$key]['fillColor'] = $value['fillColor'];
foreach ($array2 as $key2 => $value2) {
if ($value['fillColor'] == $value2['fillColor'] && $value['label'] == $value2['label']) {
$temp[$key]['data'][] = $value['data'];
if (isset($value2['data'][$i])) {
$temp[$key]['data'][] = $value2['data'][$i];
}
} else {
$temp[$key]['data'][] = $value['data'];
if (!isset($value2['data'][$i])) {
$temp[$key]['data'][] = 0;
}
}
$i++;
}
}
echo '<pre>';
print_r($temp);
Try this out:
$array1 = array(
array(
'label' => 'pending',
'fillColor' => '#468847',
'data' => '50'
),
array(
'label' => 'dispatched',
'fillColor' => '#468847',
'data' => '10'
),
array(
'label' => 'delivered',
'fillColor' => '#468847',
'data' => '8'
),
array(
'label' => 'invoiced',
'fillColor' => '#468847',
'data' => '5'
)
);
$array2 = array(
array(
'label' => 'pending',
'fillColor' => '#468847',
'data' => array()
),
array(
'label' => 'dispatched',
'fillColor' => '#6ecf70',
'data' => array()
),
array(
'label' => 'delivered',
'fillColor' => '#f89406',
'data' => array()
),
array(
'label' => 'invoiced',
'fillColor' => '#3a87ad',
'data' => array()
)
);
foreach ($array1 as $order) {
foreach ($array2 as $key => $group) {
if ($order['label'] == $group['label']) {
array_push($array2[$key]['data'], $order['data']);
}
}
}
var_dump($array2);
Declare an array of default rows with empty data values.
Merge the default array, the first array, thrn the second array into one array.
Iterate the merged array's rows.
Declare reference arrays which are identified by label values. Explicitly cast each encountered data value as an array before joining into its group's subarray.
Code: (Demo)
$defaults = [
['label' => 'pending', 'fillColor' => '#468847', 'data' => []],
['label' => 'dispatched', 'fillColor' => '#6ecf70', 'data' => []],
['label' => 'delivered', 'fillColor' => '#f89406', 'data' => []],
['label' => 'invoiced', 'fillColor' => '#3a87ad', 'data' => []],
];
$result = [];
foreach (array_merge($defaults, $array1, $array2) as $row) {
$label = $row['label'];
$row['data'] = (array) $row['data'];
if (!isset($ref[$label])) {
$ref[$label] = $row;
$result[] = &$ref[$label];
} else {
$ref[$label]['data'] = array_merge(
$ref[$label]['data'],
$row['data']
);
}
}
var_export($result);

Remove key value from array in php

This is my db result,
Array ([0] => Array ( [shopname] => Shop name [fueltype] => Pertol [amount] => 1000 )
[1] => Array ( [shopname] => dfsdfsd [fueltype] => Pertol [amount] => 54456 )
[2] => Array ( [shopname] => dfsdfsd [fueltype] => Disel [amount] => 54456 )
)
I need result like
[["Shop name", "Pertol", 1000],["dfsdfsd", "Pertol", 54456],["Shop name", "Disel", 54456]]
How to get like this, I have no idea?
array_map() along with array_values() will work for you:-
<?php
$array = Array ( '0' => Array ( 'shopname' => 'Shop name','fueltype' => 'Pertol','amount' => 1000 ),
'1' => Array ( 'shopname' => 'dfsdfsd' ,'fueltype' => 'Pertol','amount' => 54456 ),
'2' => Array ( 'shopname' => 'dfsdfsd','fueltype' => 'Disel','amount' => 54456 )
);
$values_data_only = array_map('array_values', $array);
$desire_result = json_encode($values_data_only);
echo $desire_result;
?>
Output:- https://eval.in/395344
Also via simple foreach() it is possible:-
<?php
$array = Array ( '0' => Array ( 'shopname' => 'Shop name','fueltype' => 'Pertol','amount' => 1000 ),
'1' => Array ( 'shopname' => 'dfsdfsd' ,'fueltype' => 'Pertol','amount' => 54456 ),
'2' => Array ( 'shopname' => 'dfsdfsd','fueltype' => 'Disel','amount' => 54456 )
);
$new_array = array();
foreach ($array as $k=> $arr){
$new_array[$k][] = $arr['shopname'];
$new_array[$k][] = $arr['fueltype'];
$new_array[$k][] = $arr['amount'];
}
echo "<pre/>";print_r($new_array);
$desired_result_2 = json_encode($new_array);
echo $desired_result_2;
?>
Output:-https://eval.in/395354
$mapped = array_map('array_values', $input_array); // apply filter so we dont get the keys
$json = json_encode($mapped);
Just try with:
$input = array( /* your input data */ );
$output = array();
foreach ($input as $data) {
$output[] = array_values($data);
}

How to store array as key value pair in php

I have an array $result as follows
Array
( [0] => Array (
[0] => Mr
[1] => vinay
[2] => hs
[3] => tester
[4] =>vinay.hs#abc.com
[5] => 909099
[6] => Yes )
[1] => Array (
[0] => Mr
[1] => Suresh
[2] => Kumar
[3] => tester
[4] => vinay.hs#abc.com
[5] => 809090
[6] => No )
).
I want to store this array as
Array
([0]=>Array (
[title] => Mr
[firstname] => vinay
[lastname] => hs
[job_title] => tester
[email] =>vinay.hs#abc.com
[phone] => 909099
[is_employed] => Yes )
[1] => Array (
[title] => Mr
[firstname] => Suresh
[lastname] => Kumar
[job_title] => tester
[email] => vinay.hs#abc.com
[phone] => 809090
[is_employed] => No ) ).
Explain me how to do this
$fp = fopen('foo.csv', 'r');
$fields = fgetcsv($fp); // assumes fields are the first row in the file
// or $fields = array('title', 'firstname', 'lastname', 'job_title', 'email', 'phone', 'is_employed');
$records = array();
while ($record = fgetcsv($fp))
{
$records[] = array_combine($fields, $record);
}
Obviously it needs error handling added to it.
$newarray=array();
foreach($result as $res) {
$a = array();
$i = 0;
foreach(array('title','firstname','lastname','job_title','email','phone','is_employed') as $key) {
$a[$key] = $res[$i++];
}
$newarray[] = $a;
}
$arr = array("title" => "Mr", "title" => "vinay", "key" => "value")
access it with:
$arr["title"]
array(
array(
'title' => 'Mr',
'firstname' => 'vinay',
'lastname' => 'hs',
'job_title' => 'tester',
'email' => 'vinay.hs#abc.com',
'phone' => '909099',
'is_employed' => TRUE
),
array(
'title' => 'Mr',
'firstname' => 'Suresh',
'lastname' => 'Kumar',
'job_title' => 'tester',
'email' => 'vinay.hs#abc.com',
'phone' => '809090',
'is_employed' => FALSE
)
);
UPDATED:
My answer previously is dumb. If you are loading from CSV file, assuming the first element of array is the keys.
You might want to do something like this.
Sorry for my bad naming.
$keysArray = array_shift($arrayFromCSV);
$wantedArrayStructure = array();
foreach ($arrayFromCSV as $person) {
$item = array();
foreach ($person as $key => $value) {
$item[$keysArray[$key]] = $value;
}
$wantedArrayStructure[] = $item;
}
var_dump($wantedArrayStructure);
If, is is result from msql query. You should using function to get the expected result:
mysql_fetch_assoc

Categories