[英]make array value key for another array
I have value in table like this : 我在表中有这样的价值:
id entity_id value
1 1 summer test
2 1 summer-test
3 2 winter test
4 2 winter-test
Iam using this sql query to fetch result from dbase: Iam使用此sql查询从dbase获取结果:
$query = 'SELECT entity_id,value FROM blogs';
$results = $readConnection->fetchAll($query);
It gives me result in this form: 它以这种形式给我结果:
[0] => Array
(
[entity_id] => 1 // this is common, so this should be key for new array
[value] => summer event
)
[1] => Array
(
[entity_id] => 1
[value] => summer-event
)
............... and so on....
Now I want the new array to be like this: 现在,我希望新数组如下所示:
[1] => Array
(
[name] => summer event
[path] => summer-event
)
[2] => Array
(
[name] => test event
[path] => test-event
)
I tried this: 我尝试了这个:
$newArray = [];
foreach($results as $v)
{
$newArray[$v['entity_id']] = $v['value'];
}
print_r($newArray);
It gives the last value for all entity_id 给出所有entity_id的最后一个值
Array
(
[1] => summer-test
[2] => winter-test
)
As your values are depending on your existing columns you can work try this query to get your output and then you can process your array. 由于您的值取决于现有列,因此您可以尝试使用此查询获取输出,然后处理数组。
$query = 'SELECT value AS name,REPLACE(value ,' ','-') AS path FROM blogs';
$results = $readConnection->fetchAll($query);
In 2nd column it will replace the space with your (-). 在第二列中,它将用您的(-)替换空格。
It will return you 它会回报你
[0] => Array
(
[name] => summer event
[path] => summer-event
)
[1] => Array
(
[name] => test event
[path] => test-event
)
Since you don't have the name stored in the database the only option here would be to process the resulting array before you use it. 由于您没有将名称存储在数据库中,因此这里唯一的选择是在使用结果数组之前对其进行处理。
// Create a new empty array
$proccessed_array = array();
// loop through the existing array and populate the new array
foreach ($results as $result) {
$proccessed_array[] = array(
'name' => str_replace('-', ' ', $result['value']), // You modify the path in order to be used as name
'path' => $result['value'] // You keep this value to the new array
);
}
From a dataset based on your example for $results
: 从基于您的
$results
示例的数据集中:
$results = [
[
'entity_id' => 3,
'value' => 'Fall Event',
],
[
'entity_id' => 2,
'value' => 'Summer Event',
],
[
'entity_id' => 1,
'value' => 'Spring Event',
],
[
'entity_id' => 4,
'value' => 'Winter Event',
],
];
$events = array_reduce($results, function ($carry, $item) {
$carry[$item['entity_id']] = [
'name' => $item['value'],
'path' => $item['value'],
];
return $carry;
}, $inital = []);
print_r($events);
This displays the following: 显示以下内容:
Array
(
[3] => Array
(
[name] => Fall Event
[path] => Fall Event
)
[2] => Array
(
[name] => Summer Event
[path] => Summer Event
)
[1] => Array
(
[name] => Spring Event
[path] => Spring Event
)
[4] => Array
(
[name] => Winter Event
[path] => Winter Event
)
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.